0

I have a method called Get and a call back method called X written in C# .I Have to return the _name from the Get method.But it is only possible to get the Actual value of the _name after the callback is finished.So i have to stop at the point of * until call back is finished. After that only i can return the _name .So i have to find whether the call back is finished or not.

How do i achieve a solution for above scenario? Can any one please suggest a solution for this

My methods are something like this

string _name ;

public string Get()
{
     //Some Statements
     //Asynchronous call to a method and its call back method is X


     *Want to stop here until the Call back is finished

     return _name ;
}

private void X (IAsyncResult iAsyncResult)
{
     //Call Endinvoke and get the result
     //assign the final result to global variable _name 
}
4

2 回答 2

2

使用等待句柄 IAsyncResult.AsyncWaitHandle并调用 WaitOne()。这将阻塞直到完成。

  IAsyncResult result = Something.BeginWhatever();
  result.AsyncWaitHandle.WaitOne(); //Block until BeginWhatever completes

有关更完整的示例,请参阅 msdn 文章Blocking Application Execution Using an AsyncWaitHandle

于 2012-06-18T23:29:25.307 回答
1

使用 ManualResetEvent 表示完成。

   string _name;
   ManualResetEvent _completed = new ManualResetEvent();

   public string Get()
   {
     //Some Statements
     _completed.Reset();
     //Asynchronous call to a method and its call back method is X


     //*Want to stop here until the Call back is finished
     _completed.WaitOne();

     return _name ;
   }

   private void X (IAsyncResult iAsyncResult)
   {
     //Call Endinvoke and get the result
     //assign the final result to global variable _name 
     _completed.Set();
   }
于 2012-06-19T00:20:14.613 回答