本文介绍了如何创建一个IAsyncResult立即完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现这需要 BeginDoSomething EndDoSomething 方法实现的接口。但是我的的DoSomething 是不是真的长期运行。为简单起见假设的DoSomething 只比较两个变量,并返回是否A> B

I am implementing an interface which requires implementations of BeginDoSomething and EndDoSomething methods. However my DoSomething isn't really long-running. For simplicity assume DoSomething only compares two variables and return whether a > b

所以我BeginDoSomething应该是这样的:

So my BeginDoSomething should be like:

protected override IAsyncResult BeginDoSomething(int a, int b, AsyncCallback callback, object state)
{
     bool returnValue = a > b;
     return ...; //what should I return here?  
     //The method actually already completed and I don't need to wait for anything
 }

我不知道我应该回来。我只实施 BeginDoSomething ,因为我必须这样做,不是因为我的方法是长期运行。我需要实现我自己的的IAsyncResult ?是否有一个执行已经在.NET库?

I don't know what I should return. I only implement BeginDoSomething because I have to, not because my method is long-running. Do I need to implement my own IAsyncResult? Is there an implementation already in .NET libraries?

推荐答案

做的是用委托的快速破解方式:

The quick hack way of doing it is to use a delegate:

protected override IAsyncResult BeginDoSomething(int a, int b, AsyncCallback callback, object state)
{
     bool returnValue = a > b;
     Func<int,int,bool> func = (x,y) => x > y;
     return func.BeginInvoke(a,b,callback,state);
}

该方法的缺点是,你必须要小心,如果两个线程会调用此方法的同时,你会得到一个错误。

The downside of this approach, is that you need to be careful if two threads will be calling this method concurrently you'll get an error.

这篇关于如何创建一个IAsyncResult立即完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 13:57