473,396 Members | 1,966 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,396 software developers and data experts.

Events seem to execute on a new thread - why?

First, I am not creating any new threads via invoke or any other intentional
means. As far as I know, there is just one thread, which is the main
thread.

My windows form class creates a new DeviceController() object which
initializes a serial port and defines a serial port event handler, which
processes the raw data from the serial port and then generates my custom
event (OnNewData).

public partial class LoggerForm : Form
{
DeviceController myDevice;

public LoggerForm()
{
InitializeComponent();
myDevice = new DeviceController();
myDevice.OnNewData += new
DeviceController.DeviceDataDelegate(DeviceDataEven tHandler);
}

void DeviceDataEventHandler(object sender, DeviceDataEventArgs e)
{
logTextBox.Text = e.DeviceData;
}
The consumer for my custom event is DeviceDataEventHandler(), which fires as
it should but produces the following run-time error: "Cross-thread operation
not valid: Control 'logTextBox' accessed from a thread other than the thread
it was created on."

How could this be? I thought an event was run on the same thread that
created it. It almost seems like the event is handled on a new thread.

Any ideas on why this is happening?
Thanks in advance.
Erik
Feb 11 '06 #1
4 3429
Hi Erik,
the important point is that controls should only be access from the thread
which created them. Your serial port listener is running on a seperate
thread, when data comes in it raises the event, now an event is nothing but
syntactic sugar around a multicast delegate, so the thread that received the
data is really looping through all of the event handlers in the delegates
InvocationList and calling the methods one by one, so it is not the GUI
thread running the handler it is another thread.

In your GUI code you should call invoke i.e. logTextBox.Invoke to make
sure the Main UI thread executes the update to the textbox, not the calling
thread. Also if you are performing some significant amount of processing in
the event handler you should probably use BeginInvoke rather than Invoke, to
allow the serial port handler to get back to receiving data.

Hope that helps
Mark Dawson
http://www.markdawson.org


"Erik" wrote:
First, I am not creating any new threads via invoke or any other intentional
means. As far as I know, there is just one thread, which is the main
thread.

My windows form class creates a new DeviceController() object which
initializes a serial port and defines a serial port event handler, which
processes the raw data from the serial port and then generates my custom
event (OnNewData).

public partial class LoggerForm : Form
{
DeviceController myDevice;

public LoggerForm()
{
InitializeComponent();
myDevice = new DeviceController();
myDevice.OnNewData += new
DeviceController.DeviceDataDelegate(DeviceDataEven tHandler);
}

void DeviceDataEventHandler(object sender, DeviceDataEventArgs e)
{
logTextBox.Text = e.DeviceData;
}
The consumer for my custom event is DeviceDataEventHandler(), which fires as
it should but produces the following run-time error: "Cross-thread operation
not valid: Control 'logTextBox' accessed from a thread other than the thread
it was created on."

How could this be? I thought an event was run on the same thread that
created it. It almost seems like the event is handled on a new thread.

Any ideas on why this is happening?
Thanks in advance.
Erik

Feb 12 '06 #2
Mark, that does help - I can probably solve it now.

But the basic question I'm grappling with is: why is my serial port
listener running on a separate thread in the first place? I never created a
new thread explicitly. The only thing I did as part of a method in
DeviceController is:

// create SerialPort, open COM port, add Serial Port event handler.
theSerialPort.DataReceived += new
SerialDataReceivedEventHandler(SerialDataParser);

SerialDataParser() just parses the serial port data and fires my
DeviceDataEventHandler() event. I don't understand see how this code is
running on a separate thread. I should mention this is with VS2005 and the
..NET framework 2.0.

Erik
Feb 12 '06 #3
Hi Erik,
if you look at the Microsoft documentation for the SerialPort DataReceived
event
http://msdn2.microsoft.com/en-us/lib...areceived.aspx
(watch the wrapping) it says that the DataReceived event will be raised on a
secondary thread:

"The DataReceived event is raised on a secondary thread when data is
received from the SerialPort object. Because this event is raised on a
secondary thread, and not the main thread, attempting to modify some elements
in the main thread, such as UI elements, could raise a threading exception.
If it is necessary to modify elements in the main Form or Control, post
change requests back using Invoke, which will do the work on the proper
thread."

Internally inside the SerialPort object, multiple threads are being
utilized, that is why even though you are not explicitly creating a new
thread, it is being done behind the scenes. This is a common pattern for
receiving data, there should be one thread whos job it is to receive data and
it should not spend much time processing the data, so that it can go back to
receive more data, so normally another thread is utilized to handle the data
received on the first thread.

Hope that helps
Mark Dawson
http://www.markdawson.org

"Erik" wrote:
Mark, that does help - I can probably solve it now.

But the basic question I'm grappling with is: why is my serial port
listener running on a separate thread in the first place? I never created a
new thread explicitly. The only thing I did as part of a method in
DeviceController is:

// create SerialPort, open COM port, add Serial Port event handler.
theSerialPort.DataReceived += new
SerialDataReceivedEventHandler(SerialDataParser);

SerialDataParser() just parses the serial port data and fires my
DeviceDataEventHandler() event. I don't understand see how this code is
running on a separate thread. I should mention this is with VS2005 and the
..NET framework 2.0.

Erik

Feb 12 '06 #4
I totally missed that detail (obviously). You rock! Much thanks.

Erik
Feb 12 '06 #5

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

Similar topics

2
by: Rich Tasker | last post by:
My goal is to execute a DTS package that calls multiple child DTS packages from a C# (2003) app and display the progress of the entire process to the user. I have followed the model defined in...
1
by: Jesper | last post by:
Hi, Background. In an engineering application I consider using events to control the flow in the program under the following philosophy: When a value X change it fires a "i'm changed" event. A...
2
by: Zürcher See | last post by:
The event is thread safe? If a class call a delegate for an event, is the class thread to execute the code or is the thread that has itself registered that execute the code? In few words if a form...
5
by: Bill Davidson | last post by:
Hello All: I've got a question about synchronization requiremements in a C# worker thread procedure that, among other things, sinks events from outside sources. I realize the worker thread will...
3
by: Chris Dunaway | last post by:
Consider the following simple classes/interfaces defined below. When the derived class raises the events, on which thread is the event code run? Do I need to do anything to catch the events in my...
9
by: CuriousGeorge | last post by:
Can someone explain why this code DOES NOT raise a null reference exception? //////////////////////////// Program.cs ///////////////////////////////////////////// using System; using...
15
by: colin | last post by:
Hi, Im familiar with c,c++ etc, and Ive spent a week trying to write my first app in c# it works reasonably well, but im having difficulty getting to grips with inter thread signalling etc. I...
14
by: Gotch | last post by:
Hi all, I've recently digged into C# and the whole .Net stuff. Particularly I found the idea of adding Events and Delegates to the C# language very interesting and I'm trying to use them in...
4
by: jehugaleahsa | last post by:
Hello: Is there a way to prevent one event from firing while another event is already being fired? I have a tool that extracts media from web pages and it has multiple events firing when the...
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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...
0
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...
0
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,...

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.