这是确定由TPL任务中获得,从方法返回更多的细节?

编程入门 行业动态 更新时间:2024-10-10 17:31:02
本文介绍了这是确定由TPL任务中获得,从方法返回更多的细节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我原来的方法是这样的:

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任务中获得,从方法返回更多的细节?

本文发布于:2023-11-08 06:18:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568578.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:这是   细节   方法   更多   TPL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!