简体   繁体   中英

Cancel and reactivate async task

I want to create a statusbar. The status should be set from any method inside the class. If the status is set it should be for 5000ms visible. After 5000ms the status should be empty. Sometimes it can happen, that I want to set a status when an old status is still active. For this case the old status should be overwritten and the await Task.Delay(5000); should be reset and start counting from 0.

My current code looks like this:

public CancellationTokenSource tokenSource { get; set; }
public CancellationToken token { get; set; }

public async Task SetStatusMessage(string pStatusMessage)
{
  tokenSource.Cancel();

  await Task.Run(async () =>
  {
    if (token.IsCancellationRequested)
    {
      token.ThrowIfCancellationRequested();
    }

    this.Dispatcher.Invoke(() =>
    {
      this.txtStatusMessage.Text = pStatusMessage;
    });

    await Task.Delay(5000, token);

    this.Dispatcher.Invoke(() =>
    {
      this.txtStatusMessage.Text = "";
    });
}, token);

public async void AnyMethod()
{
    await this.SetStatusMessage("Hello World");
}

This isn't working, because I cancel the task before it is running. That's why I get an OperationCanceledException (?).

This is what I would do. I have no idea why you use Task.Run() when you are using async .

public async Task SetStatusMessage(string pStatusMessage)
{
    CancellationTokenSource localToken;

    try
    {
        if (tokenSource != null)
            tokenSource.Cancel();

        tokenSource = new CancellationTokenSource();

        localToken = this.tokenSource;

        this.txtStatusMessage.Text = pStatusMessage;

        await Task.Delay(5000, localToken.token);

        this.txtStatusMessage.Text = "";
    }
    catch (TaskCanceledException) {}
    finally
    {
        localToken.Dispose();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM