Search code examples
c#.netpinvokenativemultithreading

C# Updating WinForms from NATIVE C Thread


I use a native C DLL with C# interop. I pass a delegate to native DLL as a function pointer and my method is called in C# when the native DLL wants to notify me about some event. I then want to update a TextBox on my Form. This causes unexpected issues not encountered during normal .NET only cross-thread operations. How do I update a TextBox on a form from a native thread from a C DLL?

I tried:

// Dumb approach
// causes Exception - Cross Thread Operation on GUI - expected
textBox1.Text = "some text"; 

// Invoke approach
// causes Exception (Cross Thread Operation on GUI)
textBox1.Invoke(new AddTextDelegate(AddText), new object[] { text }); 

// SynchronizationContext approach
// causes unhandled win32 exception with no call stack an no way to debug
context.Post(new SendOrPostCallback(delegate { eventHandler(this, args); }), null); 

// My own .NET thead approach
// causes unhandled win32 exception with no call stack an no way to debug
Thread thread = new Thread(new ParameterizedThreadStart(LogMethod));
thread.Start(text); 

All above except first work well if .NET threads are involved, but fail if a thread from a native DLL is involved.


Solution

  • you may take a look at this link:

    http://www.codeproject.com/Articles/16726/Cross-thread-calls-in-native-C

    It sounds like what you are searching for. I did not read it through, since it is a bit long. You may also use locked queues to put in requests. Then you can have a timer on your code side, which checks, whether there are new items within the queue, to operate. I do that sometimes, if I have lot of data coming from other thread. The invode costs also some time. It is best if you do all calculations not in the gui thread and just do the GUI updates from the GUI thread. But I think you laready know these aspects.