none
Synchronize an asynch call RRS feed

  • Question

  • I want to wait until an asynch call returns... Because I can't change the asynch part, I tried to wrap it:

     

      class MyProgram{
    
        public void execute()
        {
          AutoResetEvent auto = new AutoResetEvent(false);
          Thread t = new Thread(() => new MyClass(auto));
          t.Start();
          auto.WaitOne();
        }
      }
    
      class MyClass
      {
        private AutoResetEvent _auto;
    
        public MyClass(AutoResetEvent auto)
        {
          _auto = auto;
    
          ThirdParty tp = new ThirdParty();  //can't change this class
          tp.AsynchCall(Callback);
        }
    
        public void Callback()
        {
          _auto.Set();
        }
      }
    
    This of course doesn't work... After the constructor of MyClass is processed the thread stops and Callback() never gets called...

     

    What's best practice in this case?

    Thanks!

    Friday, October 29, 2010 1:47 PM

All replies

  • This ought to work.  Problem must be in the details with how AsyncCall is implemented.

    Just a guess, perhaps what you calling requires an STA thread.

    Use Thread.CurrentThread.SetApartmentState(ApartmentState.STA) prior to creating the ThirdParty object.

     

     

    Saturday, October 30, 2010 12:53 AM
  • It doesn't work (using an STA thread results in "Failed to set the specified COM apartment state."

     

    But why should it work at all?? I think thread t stops as soon as MyClass constructor ends...

    Wednesday, November 3, 2010 8:48 AM
  • > It doesn't work (using an STA thread

    SetApartmentState shouldn't do that.  Where did you place the call?  Do it first thing in the routine that you pass as your thread start proc.

    (Maybe you left out that you are actually using a thread pool.  In that case, adjusting the STA is a no no.  Actually create a Thread in this case to try it out.)

     

    Wednesday, November 3, 2010 10:28 PM
  • I'm not using a thread pool... I placed the call at first position:

          AutoResetEvent auto = new AutoResetEvent(false);
          Thread t = new Thread(() => 
            {
              Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
              new MyClass(auto);
            });
          t.Start();
          auto.WaitOne();
    
    Anything else I could try?

     

     

    Thursday, November 4, 2010 1:50 PM