I am looking for a way to cancel a task that was already started and then restart the same task with new input data.
Below is the sample code which I have written but it is not working.
private CancellationTokenSource _cancellationTokenSource;
public public async Task DoSomething(string input)
{
_cancellationTokenSource.Cancel(true);
_cancellationTokenSource = new CancellationTokenSource();
try
{
Task.Run(async () =>
{
//Asynchronous method code here which uses input like database operations.
await doSomeDataBaseOperationAsync(input);
}, _cancellationTokenSource.Token);
}
catch { }
}
Can someone help me with it?