473,386 Members | 1,712 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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

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

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**********************************@microsof t.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 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);
}
}
Nov 17 '05 #9

"Wilfried Mestdagh" <Wi**************@discussions.microsoft.com> wrote in
message news:F9**********************************@microsof t.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 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.


Nov 17 '05 #10
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
Nov 17 '05 #11
"Wilfried Mestdagh" <Wi**************@discussions.microsoft.com> wrote in
message news:38**********************************@microsof t.com...
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
Nov 17 '05 #12
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);
}

Nov 17 '05 #13

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

Similar topics

2
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...
12
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),...
4
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
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...
8
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...
18
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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...

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.