检查Task.Run是否尚未运行

E-B*_*Bat 2 c# asynchronous

如何检查在Task.Run as bellow 下运行的进程是否已在运行?

private async void Window_PreviewKeyDown(object sender, KeyEventArgs e){ 
    //check goes here - abort if running 
    await Task.Run(() =>  myMath.Calculate() );
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*iho 5

Task.Run()方法返回一个Task对象。您可以awaitTask对象引用分配给变量,而不是立即使用它,然后可以在以后使用它检查其状态。

例如:

private Task _task;

private async void Window_PreviewKeyDown(object sender, KeyEventArgs e){ 
    //check goes here - abort if running 
    if (_task != null && !_task.IsCompleted)
    {
        // Your code here -- use whatever mechanism you deem appropriate
        // to interrupt the Calculate() method, e.g. call Cancel() on
        // a CancellationToken you passed to the method, set a flag,
        // whatever.
    }

    Task task = Task.Run(() =>  myMath.Calculate());
    _task = task;
    await _task;
    if (task == _task)
    {
        // Only reset _task value if it's the one we created in this
        // method call
        _task = null;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,以上内容有点尴尬。在您的方案中,可能存在更好的机制来处理已经运行的任务。但是,鉴于广泛要求,我认为上述做法是合理的。

  • @NedStoyanov:使用“async”/“await”的优点之一是事件处理程序代码本身只能在单个线程中执行,使其本质上是同步的。如果用户快速单击,第二次调用事件处理程序时,处理程序的第一次执行将已经分配了`_task`变量,允许“取消先前启动的任务”逻辑(即您询问如何执行的部分)上班。 (2认同)