是否可以从TPL Task派生以从方法返回更多详细信息? [英] Is it ok to derive from TPL Task to return more details from method?
问题描述
我的原始方法如下:
string DoSomeWork();
方法 DoSomeWork
在另一个线程上开始一些工作并返回执行ID(只是随机字符串)。稍后,我可以通过返回的执行ID查询结果。重点是要在作业完成前提供执行ID。
Method DoSomeWork
starts some work on another thread and returns execution ID (just random string). Later on I can query results by the returned execution ID. Main point is to make execution ID available before job will complete.
现在,我想更改签名以返回 Task
,因此用户可以根据需要等待。
Now I want to change signature to return Task
, so user can wait if he want to.
Task DoSomeWork();
同时,我仍然需要返回执行ID(例如,用于跟踪),我看到了一些选择。首先,使用 out
参数,其次,返回具有执行ID和任务的元组(在C#中,这似乎不是最佳选择),其三,我实际上想要的
At the same time I still need to return execution ID (for tracing purposes for example) and I see a few options. First, use an out
parameter, second, return tuple with both execution ID and task (in C# this looks like not a best option), and third, about which I actually want to ask.
如果我创建一个派生 Task
的类怎么办:
What if I create a class that derives Task
:
public class ExtendedTask : Task
{
public string ExecutionID {get; set;}
}
这看起来还好吗?还是决定其他选择更好?
Does this look ok? Or is it better to decide other options?
P.S。在BCL中,有些类是从 Task
派生的。
P.S. In BCL there are some classes derived from Task
.
UPDATE ,看来我是无法对此进行足够清晰的定义。但是我需要在作业完成之前访问ExecutionID,所以我不能使用 Task.Result
。
UPDATE, seems I was not able to define this clear enough. But I need access to ExecutionID before the job completes so I cannot use Task.Result
.
推荐答案
我个人不会扩展 任务< T>
,而是撰写 。这样一来,您无需担心任何仅返回 Task< T>
的API-您只需包装任务即可。您可以拥有一个公开基础任务的属性,出于C#5异步的目的,您可以在自己的类型上实现waiter模式-但在我看来,创建自己的派生类型是可能弊大于利。
I wouldn't personally extend Task<T>
, I'd compose it instead. That way you don't need to worry about any APIs which only return Task<T>
- you can just wrap the task. You can have a property which exposes the underlying task, and for the C# 5 async purposes you can implement the awaiter pattern on your own type - but it feels to me like creating your own derived type is likely to do more harm than good. It's mostly a gut feeling though.
另一种选择是反过来工作:将您的额外状态存储在 Task.AsyncState
属性;毕竟这就是它的目的。这样一来,您就可以轻松地传递任务,而不会丢失逻辑上属于逻辑部分的执行上下文。
Another option is to work the other way round: store your extra state in the Task.AsyncState
property; that's what it's there for, after all. That way you can easily pass the task around without losing the execution context it's logically part of.
这篇关于是否可以从TPL Task派生以从方法返回更多详细信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!