How to create an IAsyncResult that exits immediately?

I am implementing an interface that requires the implementation of BeginDoSomething and EndDoSomething . However, my DoSomething not very long. For simplicity, suppose that DoSomething compares only two variables and whether a> b returns

So my BeginDoSomething should look like this:

 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 } 

I do not know what I have to return. I implement BeginDoSomething only because I have to, but not because my method is lengthy. Do I need to implement my own IAsyncResult ? Is there an implementation already in .NET libraries?

+6
c # asynchronous delegates iasyncresult
source share
2 answers

A quick way to hack 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 disadvantage of this approach is that you need to be careful that if two threads call this method at the same time, you will receive an error message.

+4
source share

It's a little quick and dirty, but you can implement a class that implements IAsyncResult like this:

  public class MyAsyncResult : IAsyncResult { bool _result; public MyAsyncResult(bool result) { _result = result; } public bool IsCompleted { get { return true; } } public WaitHandle AsyncWaitHandle { get { throw new NotImplementedException(); } } public object AsyncState { get { return _result; } } public bool CompletedSynchronously { get { return true; } } } 

Then use it in your BeginDoSomething like this:

  return new MyAsyncResult(a > b); 
+5
source share

All Articles