1

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 access 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
});
Brent
  • 1,378
  • 2
  • 16
  • 30
  • 1
    What are you asking? How to implement thread-affine class with custom Invoke method? Please make the question clearer. – Matěj Zábský Sep 22 '11 at 15:47
  • That code helps not one jot. What is your base class? – David Heffernan Sep 22 '11 at 16:55
  • @DavidHeffernan The classes I inherit from and implement are all custom, and this is a quite low level in the program chain. I'm trying to run a segment of code from a secondary thread on the main thread, see code example. – Brent Sep 22 '11 at 17:22
  • One obvious solution is to give these classes a reference to an object that can call Invoke. Can you do that? – David Heffernan Sep 22 '11 at 17:24
  • Which thread are you expecting the delegate to get executed on? – Brian Gideon Sep 22 '11 at 17:26
  • @BrianGideon main thread – Brent Sep 22 '11 at 17:32
  • @DavidHeffernan I just noticed it already has a reference to System.Windows.Forms as Invoke is from that shouldn't VS2010 at least give me the option to "Resolve" by 'using' the right collection? – Brent Sep 22 '11 at 17:34
  • @Brent No I mean that your object could call `Invoke` on an object that implements `Invoke`. For example, its parent control. – David Heffernan Sep 22 '11 at 17:35

2 Answers2

1

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 ...

Community
  • 1
  • 1
Random Dev
  • 51,810
  • 9
  • 92
  • 119
1

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.

Brent
  • 1,378
  • 2
  • 16
  • 30