gpt4 book ai didi

c# - 检查 Task.Run 尚未运行

转载 作者:行者123 更新时间:2023-12-01 23:23:19 25 4
gpt4 key购买 nike

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

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

最佳答案

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

例如:

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

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

关于c# - 检查 Task.Run 尚未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28554929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com