问题描述
我已经放在下面的什么,我试图做一些很基本的code。我有一个执行异步操作DoSomethingAshnc'方法。我想DoSomething的方法是不会在操作参数拍摄和返回一个int同步方法。
I've placed some very basic code below of what I'm trying to do. I have the 'DoSomethingAshnc' method that performs an Asynchronous operation. I would like the 'DoSomething' method to be a Synchronous method that doesn't take in the action parameter and returns an int.
public void DoSomething(Action<int> actionToPerformOnComplete)
{
DoSomethingAsync(delegate(int val)
{
actionToPerformOnComplete(val);
});
}
它甚至可能有DoSomething的返回一个整数,如果该方法是同步发生的?
Is it even possible to have 'DoSomething' return an integer as if the method was happening synchronously?
推荐答案
您就需要添加一些在你的同步方法的末尾,告诉它等待对方通话结束。我假设你的异步方法将有一个事件时,它的完成上告诉来电者。
You'd need to add something in the end of your sync method, to tell it to wait for the other call to finish. I'm assuming your async method will have an event on to tell the caller when it's finished.
如果这样的话我建议使用像一个ManualResetEvent的,在你的同步线程在等待它,并将其设置为异步之一完成事件接收器。
If so then I'd suggest using something like a ManualResetEvent, waiting on it in your sync thread, and set it in the Finish event receiver for the async one.
例如:
public void DoSomething(Action<int> actionToPerformOnComplete)
{
ManualResetEvent mre = new ManualResetEvent(false);
DoSomethingAsync(delegate(int val)
{
try
{
actionToPerformOnComplete(val);
}
finally
{
mre.Set();
}
});
mre.WaitOne();
}
这篇关于是否可以同步调用异步调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!