简体   繁体   English

取消并重新激活异步任务

[英]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.如果设置了状态,它应该是可见的 5000 毫秒。 After 5000ms the status should be empty. 5000 毫秒后,状态应为空。 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);对于这种情况,旧的状态应该被覆盖并等待 Task.Delay(5000); should be reset and start counting from 0.应重置并从 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 (?).这就是为什么我得到OperationCanceledException (?) 的原因。

This is what I would do.这就是我要做的。 I have no idea why you use Task.Run() when you are using async .我不知道你为什么在使用async时使用Task.Run()

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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