How to invoke a function on parent thread in .NET?

后端 未结 6 1110
野的像风
野的像风 2020-12-24 07:19

I have a .NET class library containing a class with a method that performs some lengthy operation. When a client calls this method it should perform the lengthy operation on

6条回答
  •  攒了一身酷
    2020-12-24 07:55

    There's no way to explicitly make code run on a specific thread, (except for the thread that was used to create UI Controls - this is an exception) but if you simply want to call code other than the code when a thread completes, You use delegates.
    First declare a delegate with the signature of the method you want to run on the new thread...

    public delegate bool CheckPrimeDelegate(long n);
    

    Then in your code, create an instance of the delegate, call it using BeginInvoke (passing any parameters it needs) and PASS a callback function delegate (OnChkPrimeDone)

    class MyClassApp
    {
       static void Main() 
       {
          CheckPrimeDelegate ckPrimDel = new CheckPrimeDelegate(Prime.Check);
    
          // Initiate the operation
          ckPrimDel.BeginInvoke(4501232117, new AsyncCallback(OnChkPrimeDone), null);
    
          // go do something else . . . .      
       }
    
       static void OnChkPrimeDone( IAsyncResult iAr)
       {
            AsyncResult ar = iAr as AsynchResult;
             CheckPrimeDelegate ckPrimDel = ar.AsyncDelegate as CheckPrimeDelegate;
             bool isPrime = ckPrimDel.EndInvoke(ar);
             Console.WriteLine(" Number is " + (isPrime? "prime ": "not prime");
       }
    }
    

    When it is done, it will call the callback function (OnChkPrimeDone)

    If you explicitly need to run this callback function on the thread that was used to create the COM Active-X object, then check the .Net Managed Code wrapper variable that holds a reference to this object... If it has a method called InvokeRequired(), then, in your callback function, test the boolean return value of this method.
    If it has InvokeRequired() method and it returns true, then the active-X object will also expose a "BeginInvoke()" Method. Then, Create ANOTHER Delegate, populated with the same function, and call BeginInvoke on the Active-X Object, passing it this new delegate... It will then run on the same thread as was used to create teh Active-X Object

    If (MyActiveXObject.InvokeRequired())
         MyActiveXObject.BeginInvoke(...);
    

提交回复
热议问题