Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对TaskCompletionSource.Task(调用了它的&x27;s.SetResult)调用ContinueWith方法安全吗?_C#_.net_Asynchronous_Task Parallel Library - Fatal编程技术网

C# 对TaskCompletionSource.Task(调用了它的&x27;s.SetResult)调用ContinueWith方法安全吗?

C# 对TaskCompletionSource.Task(调用了它的&x27;s.SetResult)调用ContinueWith方法安全吗?,c#,.net,asynchronous,task-parallel-library,C#,.net,Asynchronous,Task Parallel Library,如果已经调用了TaskCompletionSource.SetResult(…),则在TaskCompletionSource.Task上使用ContinueWith(…)方法是否安全 这一基本准则有望有助于解决以下问题: // this was written inside the question box, please excuse any silly errors and lack of error checking (I'm not near VS right now)... pri

如果已经调用了
TaskCompletionSource.SetResult(…)
,则在
TaskCompletionSource.Task
上使用
ContinueWith(…)
方法是否安全

这一基本准则有望有助于解决以下问题:

// 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*
}
//这是写在问题框内的,请原谅任何愚蠢的错误和缺少错误检查(我现在不在VS附近)。。。
private WebClient _WebClient=新WebClient();
公共任务GetExamplePage(){
var tcs=new TaskCompletionSource();
web.DownloadStringCompleted+=(s,ea)=>tcs.SetResult(ea.Result);
DownloadStringAsync(新URI)(@)http://www.example.com/example.html"));
返回tcs.task;
}
public void ProcessExamplePage(){
var task=GetExamplePage();
睡眠(1000);
task.ContinueWith(t=>Console.WriteLine(t.Result));//*行*
}
如果
WebClient.DownloadStringCompleted
事件在设置
任务之前已触发,
控制台.WriteLine(…)
是否会执行

MSDN有这样一句话():

Task.ContinueWith方法

返回的任务将不会计划执行,直到 当前任务已完成,是否由于运行到而完成 成功完成,由于未处理的异常而出错,或 由于被取消,提前退出

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


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

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

如果指定的任务在调用ContinueWith时已完成,则同步继续将在调用ContinueWith的线程上运行。

这将启动一个新的异步操作还是同步继续?因为
TaskCompletionSource
没有启动异步操作。很好。参考与此相关的文档将非常好。@annemartijn它取决于原始任务(或延续任务)是否指定了
TaskCreationOptions​.​同步运行continuations
(或
TaskContinuationOptions​.​跑​延续​异步
)​--​这些仅适用于它们的延续​--​和/或继续是否指定了
TaskContinuationOptions​.​同步执行(这适用于延续本身)。错误。例如,通过同步指定TaskContinuationOptions.ExecuteSynchronously,此文本是显式的