473,695 Members | 2,513 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

illegal cross thread operation by PostMessage

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 ?

--
rgds, Wilfried
http://www.mestdagh.biz
Nov 17 '05 #1
12 7188
Wilfried,

Without seeing the code, it is hard to say. Can you post the code you
are using?
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Wilfried Mestdagh" <Wi************ **@discussions. microsoft.com> wrote in
message news:4E******** *************** ***********@mic rosoft.com...
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 ?

--
rgds, Wilfried
http://www.mestdagh.biz

Nov 17 '05 #2
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.G etString(buffer , offset, count);
switch (rcvd) {
case UPDATE:
Main.Globals.sh owVehicles.WMUp date();

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.PostMessa ge(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
Nov 17 '05 #3
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 wrote:
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.

[snip]

thx Wilfried


Nov 17 '05 #4


"Wilfried Mestdagh" <Wi************ **@discussions. microsoft.com> wrote in
message news:38******** *************** ***********@mic rosoft.com...
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.G etString(buffer , offset, count);
switch (rcvd) {
case UPDATE:
Main.Globals.sh owVehicles.WMUp date();

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.PostMessa ge(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.PostMessa ge(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.

Nov 17 '05 #5
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
Nov 17 '05 #6
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
Nov 17 '05 #7

"Wilfried Mestdagh" <Wi************ **@discussions. microsoft.com> wrote in
message news:60******** *************** ***********@mic rosoft.com...
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


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.


Nov 17 '05 #8
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 CrossThreadButt on 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 WindowsApplicat ion1
{
partial class Form1: Form
{
const int WM_TEST = 0x400;

public Form1()
{
InitializeCompo nent();
Win32.AllocCons ole();
}

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

private void UIThreadBbutton _Click(object sender, EventArgs e)
{
Win32.PostMessa ge(Handle, WM_TEST, 0, 0);
}

private void CrossThreadBbut ton_Click(objec t sender, EventArgs e)
{
System.Threadin g.Timer T = new System.Threadin g.Timer(TimedOu t,
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.PostMessa ge(Handle, WM_TEST, 0, 0);
}

}

public class Win32
{
[DllImport("kern el32.dll")]
public static extern Boolean AllocConsole();
[DllImport("User 32.dll")]
public static extern Boolean PostMessage(Int Ptr hWnd, uint Msg, int
wParam, int lParam);
}
}
Nov 17 '05 #9

"Wilfried Mestdagh" <Wi************ **@discussions. microsoft.com> wrote in
message news:F9******** *************** ***********@mic rosoft.com...
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 CrossThreadButt on 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 WindowsApplicat ion1
{
partial class Form1: Form
{
const int WM_TEST = 0x400;

public Form1()
{
InitializeCompo nent();
Win32.AllocCons ole();
}

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

private void UIThreadBbutton _Click(object sender, EventArgs e)
{
Win32.PostMessa ge(Handle, WM_TEST, 0, 0);
}

private void CrossThreadBbut ton_Click(objec t sender, EventArgs e)
{
System.Threadin g.Timer T = new System.Threadin g.Timer(TimedOu t,
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.PostMessa ge(Handle, WM_TEST, 0, 0);
}

}

public class Win32
{
[DllImport("kern el32.dll")]
public static extern Boolean AllocConsole();
[DllImport("User 32.dll")]
public static extern Boolean PostMessage(Int Ptr hWnd, uint Msg, int
wParam, int lParam);
}
}

Here I suppose that the Handle in Win32.PostMessa ge(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;
InitializeCompo nent();
...
// Now you can safely use the member variable when you need the Handle from
another thread.
Win32.PostMessa ge(hwnd, WM_TEST, 0, 0);

Willy.


Nov 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1891
by: rob | last post by:
Dear All, I am getting an error "Illegal cross-thread operation". I am not creating any threads. I know internally there are many threads running, though. Does that mean that no form can call a function from another form even if there is a parent-child relationship? Aren't controls like TreeView based on forms. If so then why can a form containing a TreeView call members of the TreeView? If you're interested here is my scenario:
12
2372
by: [Yosi] | last post by:
What I should do to return back the permissin I had in VS2003 , that allowd me to access public methode of one Class from other Thread. I have Class A(FORM) which create new thread (new class B), the new class thread get as parameter reference to his father( CLASS who mad it (classA)), The new thread need to call methodes from his father like myfathe.methode(), This worked in VS 2003 but now in VS 2005 Beta throw an exception : An...
4
4423
by: oran johnson | last post by:
Illegal cross-thread operation: Control 'PopupInfo' accessed from a thread other than the thread it was created on. Can I track this down using the debugger? Thanks.
11
9165
by: seattleboatguy | last post by:
I am trying to send a message from a visual c++ user-thread to the main window, so the main window can update text on the window to reflect what the user-thread is doing. I have tried 2 different approaches, and both fail. I don't know what to try next. +++++++++++++++++++++++++++++++++++++++++++++++++++++ APPROACH #1: (this approach makes the most sence to me) Configure the first parameter of the thread's PostMessage() to talk to the...
8
4847
by: Pieter | last post by:
Hi, I'm having some weird problem using the BackGroundWorker in an Outlook (2003) Add-In, with VB.NET 2005: I'm using the BackGroundWorker to get the info of some mailitems, and after each item I want to raise the ProgressChanged-event to update the DataGridView. It works fine when only one Progresschanged is fired, but at the second, third, fopurth etc it raises everytile a 'Cross-thread operation not valid"-exception on lmy...
18
6588
by: Dave Booker | last post by:
I have a Thread making a callback to a Form function that alters Form data. Of course, the debugger is telling me, "Cross-thread operation not valid: Control 'FormTest' accessed from a thread other than the thread it was created on." But I am locking before I touch the shared data, so do I actually need to worry about this, or is it just the debugger being oversimplistic? Specifically, I have:
0
8623
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9113
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8976
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8830
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8820
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7655
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5837
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4339
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4575
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.