Come creare un IAsyncresult che completa immediatamente?
-
15-11-2019 - |
Domanda
Implemendo un'interfaccia che richiede implementazioni di metodi BeginDoSomething
e EndDoSomething
.Tuttavia il mio DoSomething
non è davvero lungo.
Per semplicità assumere DoSomething
confronta solo due variabili e restituire se A> B
Quindi il mio iniziale dovrebbe essere come:
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
}
.
Non so cosa dovrei tornare.Implemendo solo BeginDoSomething
perché devo, non perché il mio metodo è lungo.Devo implementare il mio IAsyncResult
?C'è un'implementazione già in librerie .NET?
Soluzione
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.
Altri suggerimenti
This is a little quick and dirty, but you can implement a class that implements IAsyncResult like so:
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);