我原来的方法是这样的:
My original method looks like:
string DoSomeWork();方法 DoSomeWork 启动其他线程并返回执行ID(只是随机字符串)一些工作。后来我可查询指定的执行ID结果。主要的一点是使执行ID可用之前的工作将完成。
Method DoSomeWork starts some work on other thread and returns execution ID (just random string). Later on I can query results by given execution ID. Main point is to make execution ID available before job will complete.
现在我想改变签名返回任务,所以用户可以等待,如果他想。
Now I want to change signature to return Task, so user can wait if he want to.
Task DoSomeWork();同时我还需要返回执行ID(用于跟踪目的,例如),我看到几个选项。首先,如果退出参数,二是既执行ID和任务返回元组(在C#这貌似不是一个最好的选择),和第三其实我是想请教一下哪些。
At the same time I still need to return execution ID (for tracing purposes for example) and I see few options. First if out parameter, second is to 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.
如果我将创建类将从工作类派生的:
What if I will create class that will derive from Task class:
public class ExtendedTask : Task { public string ExecutionID {get; set;} }这是否看起来不错?或者,它是更好地决定其他的选择?
Does this looks ok? Or it's better to decide other options?
P.S。在BCL有一些从任务类的。
P.S. In BCL there are some derived from Task classes.
更新,看来我无法确定这个明确enouthg。但我需要工作之前获得流程id就完成了,所以我不能用 Task.Result 。
UPDATE, seems I was not able to define this clear enouthg. But I need access to ExecutionID before job will complete and so I cannot use Task.Result.
推荐答案我也不会亲自延长的任务< T> ,我ð的撰写的它来代替。这样,你不必担心,只有返回任何的API 任务< T> - 你可以只是包装的任务。你可以有它的属性公开的基础任务,并为C#5异步目的,你可以实现你自己的类型awaiter模式 - 但感觉对我来说,创建自己的派生类型的可能的做弊大于利。它主要是直觉,虽然感觉。
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任务中获得,从方法返回更多的细节?
发布评论