开发者

Is it possible to call an Asynchronous call Synchronously?

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 metho开发者_运维知识库d that doesn't take in the action parameter and returns an int.

public void DoSomething(Action<int> actionToPerformOnComplete)
    {
        DoSomethingAsync(delegate(int val)
            {
                actionToPerformOnComplete(val);
            });
    }

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.

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.

Example:

public void DoSomething(Action<int> actionToPerformOnComplete)
{
   ManualResetEvent mre = new ManualResetEvent(false);
   DoSomethingAsync(delegate(int val)
   {
      try
      {
         actionToPerformOnComplete(val);
      }
      finally
      {
         mre.Set();
      }
   });
   mre.WaitOne();
}


As others have mentioned, you need to wait for your async method to finish. To do that without passing that Action parameter to your method, use this code:

public int DoSomething()
{
   int result;
   ManualResetEvent mre = new ManualResetEvent(false);
   DoSomethingAsync(val => {result = val; mre.Set(); });
   mre.WaitOne();
   return result;
}

This executes the async method, waits for it to finish and assigns the result to a local variable. This result is returned.


Yes. All you have to do is to put this line of code:

IAsyncResult asycn = ... // make a call to Async and get back IAsyncResult 
while(!asycn.IsCompleted)
{
   Thread.Sleep( ....);
}

UPDATE

Just as some asked, a correctly designed async operation will implement async pattern MSDN:

An asynchronous operation that uses the IAsyncResult design pattern is implemented as two methods named BeginOperationName and EndOperationName that begin and end the asynchronous operation OperationName respectively. For example, the FileStream class provides the BeginRead and EndRead methods to asynchronously read bytes from a file. These methods implement the asynchronous version of the Read method.


using System;
using System.Threading;

namespace qqq
{
    class Program
    {
        public static void DoAsync(Action<int> whenDone)
        {
            new Thread(o => { Thread.Sleep(3000); whenDone(42); }).Start();
        }

        static public int Do()
        {
            var mre = new ManualResetEvent(false);

            int retval = 0;
            DoAsync(i => { retval = i; mre.Set(); });

            if (mre.WaitOne())
                return retval;
            throw new ApplicationException("Unexpected error");
        }

        static void Main(string[] args)
        {
            Console.WriteLine(Do());
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜