实施明确的IAsyncResult

实施明确的IAsyncResult

本文介绍了实施明确的IAsyncResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一般警惕部分实现接口的。然而,的IAsyncResult 是一个有点特殊情况,因为它支持多种完全不同的使用模式。你多久使用/看到使用了 AsyncState / 的AsyncCallback 模式,而不是只调用 EndInvoke会,使用 AsyncWaitHandle ,或轮询 IsCompleted (呸)?

I am generally wary of implementing interfaces partially. However, IAsyncResult is a bit of a special case, given that it supports several quite different usage patterns. How often do you use/see used the AsyncState/AsyncCallback pattern, as opposed to just calling EndInvoke, using AsyncWaitHandle, or polling IsCompleted (yuck)?

相关问题:Detecting一个线程池工作项目已经完成/等待完成。

考虑这个类(非常近似的,锁定需要):

Consider this class (very approximate, locking needed):

public class Concurrent<T> {
    private ManualResetEvent _resetEvent;
    private T _result;

    public Concurrent(Func<T> f) {
        ThreadPool.QueueUserWorkItem(_ => {
                                         _result = f();
                                         IsCompleted = true;
                                         if (_resetEvent != null)
                                             _resetEvent.Set();
                                     });
    }

    public WaitHandle WaitHandle {
        get {
            if (_resetEvent == null)
                _resetEvent = new ManualResetEvent(IsCompleted);
            return _resetEvent;
        }

    public bool IsCompleted {get; private set;}
    ...

的WaitHandle (懒洋洋地创建,就像的IAsyncResult 描述文档)和 IsCompleted ,但我没有看到 AsyncState 一个合理的实现( {返回NULL;} ?)。因此,是否有意义为它实施的IAsyncResult ?需要注意的是工作中的并行扩展库并实施的IAsyncResult ,但只有 IsCompleted 是隐式实现的。

It has WaitHandle (lazily created, just as described in IAsyncResult documentation) and IsCompleted, but I don't see a sensible implementation for AsyncState ({return null;}?). So does it make sense for it to implement IAsyncResult? Note that Task in the Parallel Extensions library does implement IAsyncResult, but only IsCompleted is implemented implicitly.

推荐答案


  • 在我的经验中,只调用EndInvoke会没有任何等待或正在召回首先是很少有用

  • 只是提供回调有时是不够的,因为你的客户可能想同时等待多个操作(了WaitAny,为WaitAll)

  • 我从来没有调查IsCompleted,呸哉!所以,你可以节省IsCompleted的实施,但它是如此简单,它似乎不值得震惊的潜在客户。

所以,对于一个异步调用方法的合理的实施确实应该提供一个全面实施的IAsyncResult。

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

顺便说一句,你往往不需要实现的IAsyncResult自己,只是返回什么是Delegate.BeginInvoke返回。见System.IO.Stream.BeginRead执行的例子。

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.

这篇关于实施明确的IAsyncResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:01