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
346 views
in Technique[技术] by (71.8m points)

c# - Custom awaitables for dummies

In Async/Await FAQ, Stephen Toub says:

An awaitable is any type that exposes a GetAwaiter method which returns a valid awaiter.
...
An awaiter is any type returned from an awaitable’s GetAwaiter method and that conforms to a particular pattern.

So in order to be an awaiter, a type should:

  • Implement the INotifyCompletion interface.
  • Provide a boolean property called IsCompleted.
  • Provide a parameterless GetResult method that returns void or TResult.

(I'm ignoring ICriticalNotifyCompletion for now.)

I know the page I mentioned has a sample that shows how the compiler translates await operations but I'm stil having a hard time understanding.

When I await an awaitable,

  • When is IsCompleted checked? Where should I set it?
  • When is OnCompleted called?
  • Which thread calls OnCompleted?
  • I saw examples of both directly invoking the continuation parameter of OnCompleted and using Task.Run(continuation) in different examples, which should I go for and why?
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Why would you want a custom awaiter?

You can see the compiler's interpretation of await here. Essentially:

var temp = e.GetAwaiter();
if (!temp.IsCompleted)
{
  SAVE_STATE()
  temp.OnCompleted(&cont);
  return;

cont:
  RESTORE_STATE()
}
var i = temp.GetResult();

Edit from comments: OnCompleted should schedule its argument as a continuation of the asynchronous operation.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...