Invoking functions from a non-managed thread

kirillandy 81 Reputation points
2021-06-17T08:55:53.11+00:00

Hello! I was wondering if it is possible to Invoke/BeginInvoke a delegate from a non-managed thread.

To elaborate, I've got a Windows Forms... form which contains a little image (PictureBox object) that indicates the current state of the PC's Wi-Fi connection (online/offline).
I have registered a callback function using the WlanRegisterNotification function from the Native Wi-Fi API. Whenever the network connection state changes, my callback is executed (on a different thread, if I remember correctly) and I get the new connection state in one of the callback function parameters.

I was wondering if I could immediately BeginInvoke a delegate on my form from the callback function in order to change the image displayed in my PictureBox, but I remember vague warnings from various sources which recommend against mixing managed thread and non-managed thread code. I could not find any source that addresses my example in detail, though, and I'm having trouble deducing why my example could be a bad idea.

Has anyone attempted something like this?

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,884 questions
Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,587 questions
0 comments No comments
{count} votes

Accepted answer
  1. RLWA32 45,236 Reputation points
    2021-06-27T10:31:54.907+00:00

    A common and safe method used to initiate an update to the UI from a non-UI thread is to use a custom window message. The non-UI thread is passed the HWND of the window that handles updating on the UI thread. In your example you could use the pCallbackContext parameter to pass the HWND when you register the callback. The callback function will receive the HWND as one if its parameters. Inside the callback, use PostMessage to post the custom window message to the HWND. You would need to include code in your Winform project to recognize the custom window message and update the UI, typically with a WndProc override.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Ken Tucker 5,851 Reputation points
    2021-06-26T23:49:05.497+00:00

    You could try using a dispatch timer. when the network status needs to be changed set a property that you look for in the dispatch timer tick event. If it is set change the image


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.