是否可以从 TPL Task 派生以从方法返回更多详细信息? [英] Is it ok to derive from TPL Task to return more details from method?

查看:12
本文介绍了是否可以从 TPL Task 派生以从方法返回更多详细信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我原来的方法是这样的:

My original method looks like:

string DoSomeWork();

Method 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?

附言在 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.

推荐答案

我不会亲自扩展 Task,我会撰写 代替.这样你就不需要担心任何只返回 Task 的 API - 你可以包装任务.您可以拥有一个公开底层任务的属性,并且对于 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 Task 派生以从方法返回更多详细信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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