Implementing IAsyncResult explicitly

只谈情不闲聊 提交于 2019-12-04 05:16:39
  • In my experience, just calling EndInvoke without either waiting or being called back first is rarely useful
  • Just providing callbacks is sometimes not enough, as your clients might want to wait for multiple operations at once (WaitAny, WaitAll)
  • I've never polled IsCompleted, yuck indeed! So, you could save the implementation of IsCompleted, but it's so simple that it doesn't seem to be worth to potentially astonish your clients.

So, a reasonable implementation for an asynchronously callable method should really provide a fully implemented IAsyncResult.

BTW, you often don't need to implement IAsyncResult yourself, just return what is returned by Delegate.BeginInvoke. See the implementation of System.IO.Stream.BeginRead for an example.

It seems like you have a couple of questions. Let's handle them individually

Creating WaitHandle lazily

Yes this is the most correct approach. You should do this in a thread safe manner but lazy is the way.

The trick though is disposing of the WaitHandle. WaitHandle is a base of IDisposable and must be disposed of in a timely fashion. The documentation for IAsycResult does not cover this case. The best way to do this is in EndInvoke. The documentation for BeginInvoke explicitly states that for every BeginInvoke, there must be a corresponding EndInvoke (or BeginRead/EndRead). This is the best place in which to dispose of the WaitHandle.

How should AsyncState be implemented?

If you look at the standard BCL API's which return an IAsyncResult, most of them take a state parameter. This is typically the value that is returned from AsyncState (see the Socket API's for an example). It is a good practice to include a state variable typed as object for any API BeginInvoke style API which returns an IAsyncResult. Not necessary but good practice.

In the abscence of a state variable, returning null is acceptable.

IsCompleted API

This will be highly dependent on the implementation which creates the IAsyncResult. But yes, you should implement it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!