TaskCompletionSource:何时使用SetResult()和TrySetResult()等 [英] TaskCompletionSource : When to use SetResult() versus TrySetResult(), etc

查看:158
本文介绍了TaskCompletionSource:何时使用SetResult()和TrySetResult()等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想把头放在TPL,C#5中新的 async / await 功能以及 TaskCompletionSource .

I'm trying to wrap my head around the TPL, the new async / await features in C# 5, and the mysteries of TaskCompletionSource.

我不清楚的一件事是何时使用 SetResult SetException SetCancel TrySetResult TrySetException TrySetCancel .

One thing that isn't clear to me is when to use SetResult, SetException, and SetCancel versus TrySetResult, TrySetException and TrySetCancel.

这是MSDN必须说的:

This is what MSDN has to say:

如果Task已在其中,则此操作将返回false最终三个状态之一:RanToCompletion,错误或已取消.

This operation will return false if the Task is already in one of the three final states: RanToCompletion, Faulted, or Canceled.

如果基础Task具有以下内容,则此方法还返回false已经被处置了.

This method also returns false if the underlying Task has already been disposed.

好的,我明白了,但是它并没有真正提供何时或为何使用一种方法的指导.

Ok, I get that, but it doesn't really offer any guidance on when or why to use one over the other.

那怎么了?

推荐答案

怀疑的要点是,如果只有一件事将设置结果,则只需调用 SetResult 等.如果最终两次调用 SetResult ,则表明存在错误.(同样,如果已放置 TaskCompletionSource .)

I suspect the point is that if there's only one thing which will be setting the result, just call SetResult etc. If you end up calling SetResult twice, that indicates a bug. (Likewise if the TaskCompletionSource has been disposed.)

如果您有多个线程可能都试图同时设置结果(例如,该线程在那里指示多个并行Web服务调用中的第一个结果),请使用 TrySetResult ,因为多个线程尝试"设置结果是完全合理的,而不必知道另一个线程是否已经设置了结果.

If you've got several threads which could all be trying to set the result at the same time (e.g. it's there to indicate the first result out of several parallel web service calls) then use TrySetResult, as it's entirely reasonable for multiple threads to "try" to set the result, unaware of whether another thread has already set it.

我还没有看到任何官方指导,但这是有道理的.

I've not seen any official guidance on it, but that would make sense.

这篇关于TaskCompletionSource:何时使用SetResult()和TrySetResult()等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆