Lou*_*hys 8 .net c# delegates asynchronous iasyncresult
我正在实现一个需要实现BeginDoSomething和EndDoSomething方法的接口.然而,我DoSomething并不是真的长期奔跑.为简单起见,假设DoSomething只比较两个变量并返回是否a> b
所以我的BeginDoSomething应该是这样的:
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
}
Run Code Online (Sandbox Code Playgroud)
我不知道应该归还什么.我只是实现,BeginDoSomething因为我必须,而不是因为我的方法是长期运行.我需要实现自己的IAsyncResult吗?.NET库中是否已有实现?
这有点快速和脏,但您可以实现一个实现IAsyncResult的类,如下所示:
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; }
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的BeginDoSomething中使用它:
return new MyAsyncResult(a > b);
Run Code Online (Sandbox Code Playgroud)
快速入侵的方法是使用委托:
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);
}
Run Code Online (Sandbox Code Playgroud)
这种方法的缺点是,如果两个线程同时调用此方法,则需要小心,否则会出错.
| 归档时间: |
|
| 查看次数: |
8264 次 |
| 最近记录: |