gpt4 book ai didi

c# - 在 TaskCompletionSource.Task(已调用 .SetResult)上调用 ContinueWith 方法是否安全?

转载 作者:IT王子 更新时间:2023-10-29 04:49:31 26 4
gpt4 key购买 nike

TaskCompletionSource.Task 上使用 ContinueWith(...) 方法是否安全code> 已经被调用了吗?

这段基本代码有望帮助解决问题:

// this was written inside the question box, please excuse any silly errors and lack of error checking (I'm not near VS right now)...

private WebClient _webClient = new WebClient();

public Task<string> GetExamplePage() {

var tcs = new TaskCompletionSource<string>();

web.DownloadStringCompleted += (s, ea) => tcs.SetResult(ea.Result);

web.DownloadStringAsync(new URI(@"http://www.example.com/example.html"));

return tcs.task;
}

public void ProcessExamplePage() {

var task = GetExamplePage();

Thread.Sleep(1000);

task.ContinueWith(t => Console.WriteLine(t.Result)); // *line in question*
}

如果 WebClient.DownloadStringCompleted 事件在 task.ContinueWith 之前已经触发,Console.WriteLine(...) 是否会执行设置?

MSDN 是这样说的(Task.ContinueWith):

Task.ContinueWith Method

The returned Task will not be scheduled for execution until thecurrent task has completed, whether it completes due to running tocompletion successfully, faulting due to an unhandled exception, orexiting out early due to being canceled.

不幸的是,它没有提到如果调用此方法并且任务已经完成会发生什么。

提前感谢您提供的任何信息! :)

最佳答案

是的,这应该没问题,ContinueWith 检查前一个任务是否完成,如果是,它将立即排队继续。

关于c# - 在 TaskCompletionSource.Task(已调用 .SetResult)上调用 ContinueWith 方法是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7433603/

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