illegal cross thread operation by PostMessage

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

Using P/Invoke I use PostMessage to send a message from one thread to
another. I'm pretty sure this has already worked in dotnet. but I've
upgraded version 2 few day ago.

Now I have an illegal cross thread operation if posting a message. Is this a
bug introduced in latest version of dotnet ? It is very legal to use
postmessage because the message will execute in context of the thread the
one was posted to. Same with SendMessage.

Can someone enlighten what this is about ?
 
Wilfried,

Without seeing the code, it is hard to say. Can you post the code you
are using?
 
Hi Nicholas,
Without seeing the code, it is hard to say. Can you post the code you
are using?

I have dont workaround with an event using Invoke at the moment, But still
wonder wy the error. Here is the code. I try to explain as clear as possible.

This is called after an EndRecieve of a TCP socket when a certain packet
completely is received. this is of course not in main thread context:

private void DoDataAvailable(byte[] buffer, int offset, int count)
{
if (count <= 2)
return;
count -= 2;
string rcvd = Encoding.UTF8.GetString(buffer, offset, count);
switch (rcvd) {
case UPDATE:
Main.Globals.showVehicles.WMUpdate();

showVehicles and Globals is a form defined as follow in Main form to get it
accesible as a global:

namespace TTLocator
{
partial class Main: Form
{
public ShowVehicles showVehicles = new ShowVehicles();
static public Main Globals;

and in constructor of form:

Globals = this;

in WhowVehicles this is the called procedure:

const int WM_UPDATE = 0x401;
public void WMUpdate()
{
Win32.PostMessage(Handle, WM_UPDATE, 0, 0);
}

And this is also where the cross thread exception is coming from. Win32 is a
clas where I have my most used Win32 API calls in. PostMessage the the good
old one used to crott thread messages :)

Do I post enough to let you see my problem ?

thx Wilfried
 
Wilfried,

Continue using Control.Invoke to marshal the execution of code onto the
UI thread. It's not a workaround. It's the standard.

What error are you getting? Can post the stack trace if it is an
exception? What code is processing your user defined WM_UPDATE
message? Is it an IMessageFilter? Either way it's probably all moot
because I don't think you need to be using PostMessage anyway.

Brian
 
Wilfried Mestdagh said:
Hi Nicholas,
Without seeing the code, it is hard to say. Can you post the code
you
are using?

I have dont workaround with an event using Invoke at the moment, But still
wonder wy the error. Here is the code. I try to explain as clear as
possible.

This is called after an EndRecieve of a TCP socket when a certain packet
completely is received. this is of course not in main thread context:

private void DoDataAvailable(byte[] buffer, int offset, int count)
{
if (count <= 2)
return;
count -= 2;
string rcvd = Encoding.UTF8.GetString(buffer, offset, count);
switch (rcvd) {
case UPDATE:
Main.Globals.showVehicles.WMUpdate();

showVehicles and Globals is a form defined as follow in Main form to get
it
accesible as a global:

namespace TTLocator
{
partial class Main: Form
{
public ShowVehicles showVehicles = new ShowVehicles();
static public Main Globals;

and in constructor of form:

Globals = this;

in WhowVehicles this is the called procedure:

const int WM_UPDATE = 0x401;
public void WMUpdate()
{
Win32.PostMessage(Handle, WM_UPDATE, 0, 0);
}

And this is also where the cross thread exception is coming from. Win32 is
a
clas where I have my most used Win32 API calls in. PostMessage the the
good
old one used to crott thread messages :)

Do I post enough to let you see my problem ?

thx Wilfried

Are you sure the exception is thrown by this?
Win32.PostMessage(Handle, WM_UPDATE, 0, 0);
IMO it's not, Win32's PostMessage doesn't throw exceptions it returns error
codes.

The exception that gets thrown is new in v2.0 when running in debug mode
only, and it's an indication that you are directly touching a UI element
from the non-owning thread.

Willy.
 
Hi Willy,

The exception that gets thrown is new in v2.0 when running in debug mode
only, and it's an indication that you are directly touching a UI element
from the non-owning thread.

The exception is trow because I use Handle from other thread, that is clear.
But using a Handle does not mean I use UI, so it is a dotnet bug. Posting the
message will exectute the code that I want in the thread context of UI.

So you mean just put a silent try/catch around it and forget it ?

rgds, Wilfried
 
Hi,
The exception that gets thrown is new in v2.0 when running in debug mode
only, and it's an indication that you are directly touching a UI element
from the non-owning thread.

OK you right. I try in release mode and it works as a glance. But it is very
annoying bug because the IDE does not permit to go on. If I put a silent
exception block around it the debugger still stop but at least I can go on if
I hit F5.

rgds, Wilfried
 
Wilfried Mestdagh said:
Hi,


OK you right. I try in release mode and it works as a glance. But it is
very
annoying bug because the IDE does not permit to go on. If I put a silent
exception block around it the debugger still stop but at least I can go on
if
I hit F5.

rgds, Wilfried

This exception is thrown in debug mode by the v2.0 Forms when you try to
access a forms element from a non owning thread without marshaling the call.
However, by calling Win32's PostMessage, you directly post a message to the
message queue of the thread that owns the HWND, and because you are
bypassing the framework, NO exception CAN be thrown, besides it's perfectly
valid to call PostMessage from another thread. So once again check your code
as it looks like the exception is thrown by something else than PostMessage.

Willy.
 
Hi Willy,
However, by calling Win32's PostMessage, you directly post a message to the
message queue of the thread that owns the HWND, and because you are
bypassing the framework, NO exception CAN be thrown, besides it's perfectly
valid to call PostMessage from another thread. So once again check your code
as it looks like the exception is thrown by something else than PostMessage.

I made a little demo. As far as I can see I do nothing illegal here. If I
click the CrossThreadButton then when the threaded timer expires (in other
thread), I do the postmessage witch is (as you also say) perfecly legal and
normal way to do. Still that line generate an exception . The only option I
have at that point is 'stop debugging'. To me it is a net bug, unless I do
something wroong I dont see of course but I doupt. Can you please check
or try this code ?

namespace WindowsApplication1
{
partial class Form1: Form
{
const int WM_TEST = 0x400;

public Form1()
{
InitializeComponent();
Win32.AllocConsole();
}

protected override void WndProc(ref Message m)
{
switch (m.Msg) {
case WM_TEST:
Console.WriteLine("WndProc");
break;
default:
base.WndProc(ref m);
break;
}
}

private void UIThreadBbutton_Click(object sender, EventArgs e)
{
Win32.PostMessage(Handle, WM_TEST, 0, 0);
}

private void CrossThreadBbutton_Click(object sender, EventArgs e)
{
System.Threading.Timer T = new System.Threading.Timer(TimedOut,
null, 500, 500);
}

private void TimedOut(object state)
{
// next line generate exception error in debug mode
// and I dont access anything in this form
// unless the handle to post the message of course
Win32.PostMessage(Handle, WM_TEST, 0, 0);
}

}

public class Win32
{
[DllImport("kernel32.dll")]
public static extern Boolean AllocConsole();
[DllImport("User32.dll")]
public static extern Boolean PostMessage(IntPtr hWnd, uint Msg, int
wParam, int lParam);
}
}
 
Wilfried Mestdagh said:
Hi Willy,
However, by calling Win32's PostMessage, you directly post a message to
the
message queue of the thread that owns the HWND, and because you are
bypassing the framework, NO exception CAN be thrown, besides it's
perfectly
valid to call PostMessage from another thread. So once again check your
code
as it looks like the exception is thrown by something else than
PostMessage.

I made a little demo. As far as I can see I do nothing illegal here. If I
click the CrossThreadButton then when the threaded timer expires (in other
thread), I do the postmessage witch is (as you also say) perfecly legal
and
normal way to do. Still that line generate an exception . The only option
I
have at that point is 'stop debugging'. To me it is a net bug, unless I do
something wroong I dont see of course but I doupt. Can you please
check
or try this code ?

namespace WindowsApplication1
{
partial class Form1: Form
{
const int WM_TEST = 0x400;

public Form1()
{
InitializeComponent();
Win32.AllocConsole();
}

protected override void WndProc(ref Message m)
{
switch (m.Msg) {
case WM_TEST:
Console.WriteLine("WndProc");
break;
default:
base.WndProc(ref m);
break;
}
}

private void UIThreadBbutton_Click(object sender, EventArgs e)
{
Win32.PostMessage(Handle, WM_TEST, 0, 0);
}

private void CrossThreadBbutton_Click(object sender, EventArgs e)
{
System.Threading.Timer T = new System.Threading.Timer(TimedOut,
null, 500, 500);
}

private void TimedOut(object state)
{
// next line generate exception error in debug mode
// and I dont access anything in this form
// unless the handle to post the message of course
Win32.PostMessage(Handle, WM_TEST, 0, 0);
}

}

public class Win32
{
[DllImport("kernel32.dll")]
public static extern Boolean AllocConsole();
[DllImport("User32.dll")]
public static extern Boolean PostMessage(IntPtr hWnd, uint Msg, int
wParam, int lParam);
}
}


Here I suppose that the Handle in Win32.PostMessage(Handle, WM_TEST, 0, 0);
is the Form1.Handle property, right?

When calling PostMessage from the non UI thread, you are directly accessing
the Handle (HWND) from the non owning thread, which is now checked by the
framework in debug mode as a safety measure.
What you could do to bypass the check is store the Handle in class variable,
and use that value when calling PostMessage.

partial class Form1: Form
{
IntPtr hwnd;
public IntPtr HWND
{
get {return hwnd;}
}
const int WM_TEST = 0x400;
public Form1()
{
// store window handle in member variable
hwnd = this.Handle;
InitializeComponent();
...
// Now you can safely use the member variable when you need the Handle from
another thread.
Win32.PostMessage(hwnd, WM_TEST, 0, 0);

Willy.
 
Hi Willy,
What you could do to bypass the check is store the Handle in class variable,
and use that value when calling PostMessage.

Thank you. I tryed and it works as a glance. Thx :)

rgds, Wilfried
 
Wilfried Mestdagh said:
const int WM_UPDATE = 0x401;
public void WMUpdate()
{
Win32.PostMessage(Handle, WM_UPDATE, 0, 0);
}

I'm using MS C# .Net, and can't find the "Win32.PostMessage" function.
I found a "Microsoft.Win32" namespace, but no PostMessage function.
Where is this function buried?

Thanks
DanB
 
you have to make them yourself. I have most importand of them in a separate
class, here is importand part:

#region Using directives

using System;
using System.Text;
using System.Xml;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices; // needed to call external
application (winAPI dll)
#endregion

namespace Mestdagh.biz
{
public class Win32
{
[DllImport("kernel32.dll")]
public static extern Boolean AllocConsole();
[DllImport("User32.dll")]
public static extern IntPtr FindWindow(string ClassName, string
WindowName);
[DllImport("User32.dll")]
public static extern Boolean PostMessage(IntPtr hWnd, uint Msg,
IntPtr wParam, IntPtr lParam);
[DllImport("User32.dll")]
public static extern Boolean SendMessage(IntPtr hWnd, uint Msg,
IntPtr wParam, IntPtr lParam);
[DllImport("User32.dll")]
public static extern Int32 SetForegroundWindow(int hWnd);
[DllImport("User32.dll")]
public static extern Int32 GetWindowText(int hWnd, StringBuilder s,
int nMaxCount);
[DllImport("User32.dll")]
public static extern Int32 GetWindowTextLength(int hwnd);
[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
public static extern int GetDesktopWindow();
[DllImport("User32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, int
dwFlags, int dwExtraInfo);
}
 
Back
Top