明确地超时事件不是一个好方法。你可能想调查
Cancel Async Tasks after a Period of Time.
您可以在一段时间后取消异步操作
如果您不想,请使用 CancellationTokenSource.CancelAfter 方法
等待操作完成。该方法调度
取消任何未完成的相关任务
CancelAfter 表达式指定的时间段。
来自 MSDN 的示例代码:
// Declare a System.Threading.CancellationTokenSource.
CancellationTokenSource cts;
private async void startButton_Click(object sender, RoutedEventArgs e)
{
// Instantiate the CancellationTokenSource.
cts = new CancellationTokenSource();
resultsTextBox.Clear();
try
{
// ***Set up the CancellationTokenSource to cancel after 2.5 seconds. (You
// can adjust the time.)
cts.CancelAfter(2500);
await AccessTheWebAsync(cts.Token);
resultsTextBox.Text += "\r\nDownloads succeeded.\r\n";
}
catch (OperationCanceledException)
{
resultsTextBox.Text += "\r\nDownloads canceled.\r\n";
}
catch (Exception)
{
resultsTextBox.Text += "\r\nDownloads failed.\r\n";
}
cts = null;
}
// You can still include a Cancel button if you want to.
private void cancelButton_Click(object sender, RoutedEventArgs e)
{
if (cts != null)
{
cts.Cancel();
}
}
async Task AccessTheWebAsync(CancellationToken ct)
{
// Declare an HttpClient object.
HttpClient client = new HttpClient();
// Make a list of web addresses.
List<string> urlList = SetUpURLList();
foreach (var url in urlList)
{
// GetAsync returns a Task<HttpResponseMessage>.
// Argument ct carries the message if the Cancel button is chosen.
// Note that the Cancel button cancels all remaining downloads.
HttpResponseMessage response = await client.GetAsync(url, ct);
// Retrieve the website contents from the HttpResponseMessage.
byte[] urlContents = await response.Content.ReadAsByteArrayAsync();
resultsTextBox.Text +=
String.Format("\r\nLength of the downloaded string: {0}.\r\n"
, urlContents.Length);
}
}
还有Thread.Abort Method会终止线程。
编辑: 取消任务 - 更好的解释 (source)
Task 类提供了一种基于 CancellationTokenSource 类取消已启动任务的方法。
取消任务的步骤:
异步方法应该除了CancellationToken类型的参数
创建 CancellationTokenSource 类的实例,例如:var cts = new CancellationTokenSource();
将 CancellationToken 从实例传递到异步方法,例如:Task<string> t1 = GreetingAsync("Bulbul", cts.Token);
-
从长时间运行的方法中,我们必须调用 CancellationToken 的 ThrowIfCancellationRequested() 方法。
static string Greeting(string name, CancellationToken token)
{
Thread.Sleep(3000);
token. ThrowIfCancellationRequested();
return string.Format("Hello, {0}", name);
}
在我们等待任务的地方找到OperationCanceledException。
我们可以通过调用CancellationTokenSource实例的Cancel方法取消操作,OperationCanceledException会从长时间运行的操作中抛出。我们也可以设置时间取消对实例的操作。
更多详情 - MSDN Link。
static void Main(string[] args)
{
CallWithAsync();
Console.ReadKey();
}
async static void CallWithAsync()
{
try
{
CancellationTokenSource source = new CancellationTokenSource();
source.CancelAfter(TimeSpan.FromSeconds(1));
var t1 = await GreetingAsync("Bulbul", source.Token);
}
catch (OperationCanceledException ex)
{
Console.WriteLine(ex.Message);
}
}
static Task<string> GreetingAsync(string name, CancellationToken token)
{
return Task.Run<string>(() =>
{
return Greeting(name, token);
});
}
static string Greeting(string name, CancellationToken token)
{
Thread.Sleep(3000);
token.ThrowIfCancellationRequested();
return string.Format("Hello, {0}", name);
}