C#如何通过单击另一个按钮来取消task.run? [英] C# how to cancel task.run by click on another button?
本文介绍了C#如何通过单击另一个按钮来取消task.run?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
hi
i希望通过点击另一个按钮取消当前任务
如何?
我有什么试过:
hi
i want cancel current task run by click on another button
how?
What I have tried:
private async void Search_Button_ClickAsync(object sender, EventArgs e)
{
await (Task.Run(() =>
//... my program
));
}
private async void CancelButton_ClickAsync(object sender, EventArgs e)
{
// i want cancel by click this button
}
推荐答案
您可以使用 CancellationTokenSource 执行此操作,请参阅此处的示例:并行编程:任务取消| C#常见问题解答 [ ^ ]
您将需要以下语法:
You can do this with a CancellationTokenSource see example here: Parallel Programming: Task Cancellation | C# Frequently Asked Questions[^]
You will need this syntax though:
Task.Factory.StartNew()
您需要在方法中检查是否已请求取消。以下是来自ViewModel的片段,用于显示您需要的模式。
You need to check within your method to see if cancellation has been requested. Here is a snippet from a ViewModel to show the sort of pattern you need.
private CancellationTokenSource cts;
//called from a 'start' button click
private async void OnStartAsync(object arg)
{
IsStarted = true;
cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
try
{
//this runs your asynchronous method
//you must check periodically to see
//if cancellation has been requested
await Task.Run(() =>
{
while (true)
{
Thread.Sleep(100);
//check to see if operation is cancelled
//and throw exception if it is
token.ThrowIfCancellationRequested();
}
},token);
}
catch (OperationCanceledException)
{
IsStarted = false;
}
}
private bool isStarted;
public bool IsStarted
{
get
{
return isStarted;
}
set
{
isStarted = value;
StartCommand.RaiseCanExecuteChanged();
CancelCommand.RaiseCanExecuteChanged();
}
}
//called from a 'cancel' button
private void OnCancel(object arg)
{
cts.Cancel();
}
这篇关于C#如何通过单击另一个按钮来取消task.run?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文