Home > Software design >  Cancelling an Async Task When TextBox Text Changed Then Restart It
Cancelling an Async Task When TextBox Text Changed Then Restart It

Time:01-03

I've .NET app and there area DataGridView and TextBox on my GUI. What I want to do is when user change TextBox text, update DataGridView where cells contains this text. But this search should run as async task because if it's not, it causes freeze on GUI. Everytime when user changed TextBox text, my app should cancel if another search task running and rerun it again to search according to new search values. Here is my code;

CancellationTokenSource cts = new CancellationTokenSource();
private async void TextBox1_Changed(object sender, EventArgs e)    
{
    cts.Cancel();
    CancellationToken ct = cts.Token;
    try
    {
        await Task.Run(() =>
        {
            System.Diagnostics.Debug.WriteLine("Task started");

            // Searching here.

            System.Diagnostics.Debug.WriteLine("Task finished");
        }, cts.Token);
    }
    catch
    {
        System.Diagnostics.Debug.WriteLine("Cancelled");
    }
}

On my code, tasks are canceled without it's started. I only see "Cancelled" line on debug console. I should cancel tasks because if I don't their numbers and app's CPU usage increases. Is there way to do that ?

CodePudding user response:

Like Rand Random said, i should decleare new CancellationTokenSource object. I have edited my code like this and it's worked. Code should be like that:

CancellationTokenSource cts = new CancellationTokenSource();
private async void TextBox1_Changed(object sender, EventArgs e)    
{
    cts.Cancel();
    cts.Dispose();
    cts = new CancellationTokenSource();
    try
    {
        await Task.Run(() =>
        {
            System.Diagnostics.Debug.WriteLine("Task started");

            // Searching here.

            System.Diagnostics.Debug.WriteLine("Task finished");
        }, cts.Token);
    }
    catch
    {
        System.Diagnostics.Debug.WriteLine("Cancelled");
    }
}

CodePudding user response:

Check to see if it cancels the operation with a token

change your code to :

 CancellationTokenSource cts = new CancellationTokenSource();
 private async void TextBox1_Changed(object sender, EventArgs e)
 {
    CancellationToken token = cts.Token;
    if (token.CanBeCanceled)
        cts.Cancel();

    try
    {
        await Task.Run(() =>
        {
            System.Diagnostics.Debug.WriteLine("Task started");

            // Searching here.

             System.Diagnostics.Debug.WriteLine("Task finished");
         }, token);
     }
     catch
     {
        System.Diagnostics.Debug.WriteLine("Cancelled");
     }
     finally {
       cts.Dispose();
     }
}
  • Related