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

后端 未结 4 1660
故里飘歌
故里飘歌 2020-12-15 20:15

My original method looks like:

string DoSomeWork();

Method DoSomeWork starts some work on another thread and returns execution

4条回答
  •  一向
    一向 (楼主)
    2020-12-15 20:59

    I wouldn't personally extend Task, I'd compose it instead. That way you don't need to worry about any APIs which only return Task - 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.

提交回复
热议问题