检查 Task.Run 尚未 运行

Check Task.Run Is Not Already Running

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

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

Task.Run() 方法 returns 一个 Task 对象。您可以不立即使用 await,而是将 Task 对象引用分配给一个变量,稍后您可以使用它来检查其状态。

例如:

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

请注意,上面的内容有点尴尬。在您的场景中,可能有更好的机制来处理已经 运行 的任务。但考虑到广泛规定的要求,我认为上述是一种合理的做法。