473,789 Members | 2,706 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can a thread only be a method?

I've using thread a lot in C#, but all of them were just single method
with no return value or paramenters. It may sound bizarre but, can't
it be a class?

I'm writing an Windows application that processes inputs from a serial
port. The serial port data is processed when DataReceived event occurs
from the SerialPort instance. If the DataReceived event handler and
the MainForm are in the same thread, and the user is calling a method
in the Mainform which possibly take a few seconds, and if data is
received at that time, I worry that event might not be handled. So I
want to run serial port handler class in a separate thread but all I
know is to run a method as a thread.

//A method that takes 5 seconds
void OnMenuClicked(o bject sender, EventArgs e)
{
//Now 00:00:00
doing some work.....
//Now 00:00:05
}

void SerialPort_Data Receved(....)
{
//If this happend at 00:00:02, would it be processed?
}

If running a class as a separate class is a stupid idea, what should I
do to ensure the DataReceived events be processed properly even if the
MainForm is busy?

Thank you very much.

Feb 18 '07 #1
7 1976
Sin Jeong-hun wrote:
I've using thread a lot in C#, but all of them were just single method
with no return value or paramenters. It may sound bizarre but, can't
it be a class?
A thread executes code. Code has to be in a method. A method has to be
in a class.
I'm writing an Windows application that processes inputs from a serial
port. The serial port data is processed when DataReceived event occurs
from the SerialPort instance. If the DataReceived event handler and
the MainForm are in the same thread, and the user is calling a method
in the Mainform which possibly take a few seconds, and if data is
received at that time, I worry that event might not be handled. So I
want to run serial port handler class in a separate thread but all I
know is to run a method as a thread.

//A method that takes 5 seconds
void OnMenuClicked(o bject sender, EventArgs e)
{
//Now 00:00:00
doing some work.....
//Now 00:00:05
}

void SerialPort_Data Receved(....)
{
//If this happend at 00:00:02, would it be processed?
}

If running a class as a separate class is a stupid idea, what should I
do to ensure the DataReceived events be processed properly even if the
MainForm is busy?
Separate thread running a method - possible updating the form
via Invoke.

Arne
Feb 18 '07 #2
On Feb 17, 6:55 pm, "Sin Jeong-hun" <typing...@gmai l.comwrote:
I've using thread a lot in C#, but all of them were just single method
with no return value or paramenters. It may sound bizarre but, can't
it be a class?

I'm writing an Windows application that processes inputs from a serial
port. The serial port data is processed when DataReceived event occurs
from the SerialPort instance. If the DataReceived event handler and
the MainForm are in the same thread, and the user is calling a method
in the Mainform which possibly take a few seconds, and if data is
received at that time, I worry that event might not be handled. So I
want to run serial port handler class in a separate thread but all I
know is to run a method as a thread.

//A method that takes 5 seconds
void OnMenuClicked(o bject sender, EventArgs e)
{
//Now 00:00:00
doing some work.....
//Now 00:00:05

}

void SerialPort_Data Receved(....)
{
//If this happend at 00:00:02, would it be processed?

}

If running a class as a separate class is a stupid idea, what should I
do to ensure the DataReceived events be processed properly even if the
MainForm is busy?
>From the documentation:
"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."

In other words, your SerialPort_Data Received event is _always_ called
on a secondary thread. You don't have a choice in the matter. So, it
can _never_ be blocked by UI activity.

The real question is how to make changes to your user interface
(Controls) as a result of what is received from the serial port. The
doc tells you one way (although not the only way) to do that.

Feb 18 '07 #3
On Feb 18, 2:01 pm, "Bruce Wood" <brucew...@cana da.comwrote:
On Feb 17, 6:55 pm, "Sin Jeong-hun" <typing...@gmai l.comwrote:
I've using thread a lot in C#, but all of them were just single method
with no return value or paramenters. It may sound bizarre but, can't
it be a class?
I'm writing an Windows application that processes inputs from a serial
port. The serial port data is processed when DataReceived event occurs
from the SerialPort instance. If the DataReceived event handler and
the MainForm are in the same thread, and the user is calling a method
in the Mainform which possibly take a few seconds, and if data is
received at that time, I worry that event might not be handled. So I
want to run serial port handler class in a separate thread but all I
know is to run a method as a thread.
//A method that takes 5 seconds
void OnMenuClicked(o bject sender, EventArgs e)
{
//Now 00:00:00
doing some work.....
//Now 00:00:05
}
void SerialPort_Data Receved(....)
{
//If this happend at 00:00:02, would it be processed?
}
If running a class as a separate class is a stupid idea, what should I
do to ensure the DataReceived events be processed properly even if the
MainForm is busy?
From the documentation:

"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."

In other words, your SerialPort_Data Received event is _always_ called
on a secondary thread. You don't have a choice in the matter. So, it
can _never_ be blocked by UI activity.

The real question is how to make changes to your user interface
(Controls) as a result of what is received from the serial port. The
doc tells you one way (although not the only way) to do that.
Thank you. Till .NET 1.1, I could access the UI objects within
separate threads,
but with .NET 2.0, this caused InvalidOperatio nException. I was aware
of
this problem since I migrated to the .NET 2.0, so I know how to handle
this
using delegates and Invoke.

I mainly use C#, but for this project I'm actually using VB.NET. Since
VB.NET
and C# use the same base class library, I asked this question here.
(I'm sorry if
you think it was wrong) I added SerialPort WithEvents to the MainForm
and
accessed UI objects (TextBox.Append Text() to be exact)
within SerialPort_Data Received, but it didn't cause
InvalidOperatio nException.
So I thought that SerialPort_Data Received method was running on the
same
thread as the MainForm. Maybe that was VB.NET specific, I guess I have
to
try the same code in C#.

Thank you, Mr. Bruce Wood.

Feb 19 '07 #4
On Feb 18, 5:03 pm, "Sin Jeong-hun" <typing...@gmai l.comwrote:
On Feb 18, 2:01 pm, "Bruce Wood" <brucew...@cana da.comwrote:
On Feb 17, 6:55 pm, "Sin Jeong-hun" <typing...@gmai l.comwrote:
I've using thread a lot in C#, but all of them were just single method
with no return value or paramenters. It may sound bizarre but, can't
it be a class?
I'm writing an Windows application that processes inputs from a serial
port. The serial port data is processed when DataReceived event occurs
from the SerialPort instance. If the DataReceived event handler and
the MainForm are in the same thread, and the user is calling a method
in the Mainform which possibly take a few seconds, and if data is
received at that time, I worry that event might not be handled. So I
want to run serial port handler class in a separate thread but all I
know is to run a method as a thread.
//A method that takes 5 seconds
void OnMenuClicked(o bject sender, EventArgs e)
{
//Now 00:00:00
doing some work.....
//Now 00:00:05
}
void SerialPort_Data Receved(....)
{
//If this happend at 00:00:02, would it be processed?
}
If running a class as a separate class is a stupid idea, what should I
do to ensure the DataReceived events be processed properly even if the
MainForm is busy?
>From the documentation:
"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."
In other words, your SerialPort_Data Received event is _always_ called
on a secondary thread. You don't have a choice in the matter. So, it
can _never_ be blocked by UI activity.
The real question is how to make changes to your user interface
(Controls) as a result of what is received from the serial port. The
doc tells you one way (although not the only way) to do that.

Thank you. Till .NET 1.1, I could access the UI objects within
separate threads,
Well, you could and you couldn't. You could, but it would cause random
cross-threading errors. The docs tell you not to, and if you do it in
1.1 it _will_ occasionally crash your app. However, many people didn't
know this because they did it anyway and it often worked.
but with .NET 2.0, this caused InvalidOperatio nException. I was aware
of this problem since I migrated to the .NET 2.0, so I know how to handle
this using delegates and Invoke.
Invoke is one way to handle the problem. The other way (which may be
better in your case) is a neutral data structure accessed from both
threads. See below for more info.
I mainly use C#, but for this project I'm actually using VB.NET. Since
VB.NET
and C# use the same base class library, I asked this question here.
(I'm sorry if
you think it was wrong) I added SerialPort WithEvents to the MainForm
and
accessed UI objects (TextBox.Append Text() to be exact)
within SerialPort_Data Received, but it didn't cause
InvalidOperatio nException.
So I thought that SerialPort_Data Received method was running on the
same
thread as the MainForm. Maybe that was VB.NET specific, I guess I have
to
try the same code in C#.
No, it's not VB specific. The Framework is language-neutral, so if you
believe the docs then DataReceived is always called on a non-UI
thread, and you should always marshal back onto the UI thread in order
to update the UI.

There is one simple way to tell whether your method is running on a
secondary thread: Simply write to a log file the value of some
control's InvokeRequired property. If it's true (it should be) then
you're running on a non-UI thread. You can always try popping a
MessageBox containing the value, but then this may crash your app. :-)

Invoke is one way to get back onto the UI thread, but in your case it
may cause a problem. Depending upon how often you're getting those
DataReceived events, you may overload the UI thread with invoke
requests. You see, all Invoke really does is package up a method call
in a data structure and queue it to be processed later on the UI
thread, where "queue it" means, literally, sticking the data structure
on a queue in memory, where the UI thread will grab it later in order
to actually call the method.

If you Invoke onto the UI thread faster than the UI thread can pick
those requests off the queue and call the invoked method, then the
queue just keeps getting bigger and bigger and the UI farther and
farther behind the serial port. If you're receiving an event every
second or so, it's probably OK, but if you're receiving 100 or even 10
events a second, you may have problems.

Another possible solution is a neutral data structure: your
DataReceived method updates a data structure, and your UI then polls
that data structure from time to time and updates the UI with changes.
No Invoke required: the DataReceived method writes to the data
structure, and the UI reads it. The only thing you have to do is take
out a lock on the data structure while reading and writing to ensure
that one isn't reading while the other is writing.

So, there you have it: two possible solutions, depending upon your
situation.

Feb 19 '07 #5
"Sin Jeong-hun" <ty*******@gmai l.comwrote:
I've using thread a lot in C#, but all of them were just single method
with no return value or paramenters. It may sound bizarre but, can't
it be a class?
It's easy enough to tie a thread to a class - in fact languages like Java
require just this (IIRC).

This is very easy to do in C#:

public class Foo
{
private Thread _t;
public Foo()
{
_t = new Thread(startup) ;
_t.start();
}
private void Startup()
{
// Now we're in a method in the class. Can do anything here...
}
}

(This code is psudo code - I just typed it in here...)

--
Chris Mullins, MCSD.NET, MCPD:Enterprise , Microsoft C# MVP
http://www.coversant.com/blogs/cmullins
Feb 19 '07 #6
"Sin Jeong-hun" <ty*******@gmai l.comwrote in message
news:11******** *************@p 10g2000cwp.goog legroups.com...
I'm writing an Windows application that processes inputs from a serial
port. The serial port data is processed when DataReceived event occurs
from the SerialPort instance. If the DataReceived event handler and
the MainForm are in the same thread, and the user is calling a method
in the Mainform which possibly take a few seconds, and if data is
received at that time, I worry that event might not be handled. So I
want to run serial port handler class in a separate thread but all I
know is to run a method as a thread.
You actually don't want to really use custom threads for this - you're
better off using Asynchronous I/O.

If you poke around the methods that you're calling, you'll find a
"BeginRead( ..)" method in there. Look that up in the help, and figure out
how to take advantage of it. That's really the best way for you to be doing
I/O from the Serial Port...

--
Chris Mullins, MCSD.NET, MCPD:Enterprise , Microsoft C# MVP
http://www.coversant.com/blogs/cmullins
Feb 19 '07 #7
On Feb 20, 3:08 am, "Chris Mullins [MVP]" <cmull...@yahoo .comwrote:
"Sin Jeong-hun" <typing...@gmai l.comwrote in message

news:11******** *************@p 10g2000cwp.goog legroups.com...
I'm writing an Windows application that processes inputs from a serial
port. The serial port data is processed when DataReceived event occurs
from the SerialPort instance. If the DataReceived event handler and
the MainForm are in the same thread, and the user is calling a method
in the Mainform which possibly take a few seconds, and if data is
received at that time, I worry that event might not be handled. So I
want to run serial port handler class in a separate thread but all I
know is to run a method as a thread.

You actually don't want to really use custom threads for this - you're
better off using Asynchronous I/O.
Thank you.
>
If you poke around the methods that you're calling, you'll find a
"BeginRead( ..)" method in there. Look that up in the help, and figure out
how to take advantage of it. That's really the best way for you to be doing
I/O from the Serial Port...

--
Chris Mullins, MCSD.NET, MCPD:Enterprise , Microsoft C# MVPhttp://www.coversant.c om/blogs/cmullins

Feb 24 '07 #8

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

Similar topics

16
2052
by: Alvin Bruney | last post by:
I'm observing that a sleeping thread changes to stopped after a while. Is that accepted framework behavior for web applications? My thread basically does some work, and sleeps for 60 minutes before calling itself recursively, which means it is supposed to run on the hour every hour. But it automatically stops after 2 hours. I only get 2 emails, 1 per hour and then nothing. When I examine the threadstate during run-time, it has changed...
5
4031
by: Serge | last post by:
Hi, I am having a thread hang problem in my c# code. The example on the website: http://csharp.web1000.com/ is a simplified version of my problem. You will see in the form that a method TestThread increments a number in the textbox on the form. TestThread is called from a worker thread (2nd thread) using a TimerThread.
12
2336
by: Ricardo Pereira | last post by:
Hello all, I have a C# class (in this example, called A) that, in its constructor, starts a thread with a method of its own. That thread will be used to continuously check for one of its object's state and generate classe's A events "Connected" and "Disconnected". It looks something like this: "
13
5097
by: Bob Day | last post by:
Using vs2003, vb.net I start a thread, giving it a name before start. Code snippet: 'give each thread a unique name (for later identification) Trunk_Thread.Name = "Trunk_0_Thread" ' allow only 1 thread per line Trunk_Thread.ApartmentState = ApartmentState.STA
4
2561
by: fred | last post by:
I use a Synclock in a secondary thread and also stop the thread using the abort method. If the abort occurs while the thread is in the Synclock will the SyncLock always be released before the thread stops or do I need to add some extra code to avoid Synclock staying on after the thread has been stopped. Thanks Fred
3
1894
by: JohnnyGr | last post by:
I have heard theres a new way to start threads with parameters in framework 2.0, does anyone know how to do that? this is what i need to do... Start a thread that executes some stuff, in this case it does gets all files from a directory. then i need to update the GUI with information from the thread... the thread should be started with a parameter, in this case its a string
5
2807
by: Alan T | last post by:
I will do several things in my thread: Copy a file to a location Update database record Read the file content Write the content to a log file If I call Thread.Abort(), it may be possible to stop at the middle of the something ?
2
1963
by: Don | last post by:
How to stop a process which is running in a separate thread!!! I've got a class which performs some lengthy process in a background (separate) thread. And this lengthy process raises events regularly to inform the main thread of the progress (which is then displayed to the user). Since the event is raised from another thread, i've used me.Invoke() to update the ui properly. However, my problem is in cancelling the process. I need to...
6
2945
by: mehdi | last post by:
Hi folks, You know, the Thread class has got a method named Abort which according to the msdn: "Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread." I've had a long discussion with someone on not to use the mentioned method unless under the most extreme cases. I believe that it's
0
9666
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
10200
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
10139
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
9984
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...
1
7529
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6769
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
5418
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
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4093
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.