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?
DoSomethingyou can simply call_cancellationTokenSource.Cancel(true);which will cancel the task and then call the method again. Is it not working? - RBTcancellationTokenSource.Cancel(true);this code before initialization, does it work ? - Mrinal KambojcancellationTokenSourcevariable insideDoSomethingmethod? It doesn't seem to be defined anywhere in your code block. - RBT