Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

c# - Is it ok to derive from TPL Task to return more details from method?

My original method looks like:

string DoSomeWork();

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.

Now I want to change signature to return Task, so user can wait if he want to.

Task DoSomeWork();

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.

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. In BCL there are some classes derived from Task.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...