如何检查在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)
该Task.Run()方法返回一个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;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,以上内容有点尴尬。在您的方案中,可能存在更好的机制来处理已经运行的任务。但是,鉴于广泛要求,我认为上述做法是合理的。
| 归档时间: |
|
| 查看次数: |
1219 次 |
| 最近记录: |