开发者

Control.Invoke does not exist in the current context

开发者 https://www.devze.com 2023-04-06 23:04 出处:网络
Error: The name \'Invoke\' does not exist in the current context The class I am working on already has a base class so I can\'t have it implement something like Windows.Forms.Control.

Error: The name 'Invoke' does not exist in the current context

The class I am working on already has a base class so I can't have it implement something like Windows.Forms.Control.

I looked at article here but I don't want to implement another interface, and don't know what I would put in the methods.

This is a fairly low level C# adaptor program so it doesn't have a开发者_高级运维ccess to the libraries most UI stuff would

EDIT I'm trying to do something like this

// On thread X   
Invoke((m_delegate)delegate(){
// Do something on main thread
});


it's hard to tell from the little you told about your code but maybe you can use System.Threading.SynchronizationContext to do the stuff you want.

You just have to capture the context in your UI-thread (for example by constructing your object there) and simulate Control.Invoke with SynchronizationContext.Post:

class MyObj
{
   SynchronizationContext _context;

   // please Note: construct the Objects in your main/ui thread to caputure the
   // right context
   public MyObj()
   {
     CaptureCurrentContext();
   }

   // or call this from your main/UI thread
   public void CaptureCurrentContext()
   {
      _context = SynchronizationContext.Current;
   }

   public void MyInvoke(Action a)
   {
       _context.Post((SendOrPostCallback)(_ => a()), null);
   }
}

BTW: here is a very good Answer to allmost the same question: Using SynchronizationContext for sending ...


I ended up using Action delegate with an anonymous method, that is passed in an object to the right thread, and then executed. Works great and I find this code pretty sexy.

0

精彩评论

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