Lets say you have a GUI thread. When pressing a button the GUI thread creates
a thread which listens to a COM port. When the COM port listening thread gets
input from the COM port it wants to use this information from the COM port to
display in the GUI. Which is the best way to do this?
E g
class MyGUIclass
{
public delegate void DataInput(object sender, StringEventArgs evArgs);
public event DataInput OnDataInput;
public MyGUIclass()
{
InitializeComponent();
OnDataInput += new DataInput(DataInputHandler);
}
private void button_click(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(DataInThread), new
object[] { "COM1", 9600 });
}
}
protected void DataInThread(object parameter)
{
if (parameter.GetType() != typeof(object[]))
{
return;
}
object[] l_params = (object[]) parameter;
if (l_params.Length != 2)
{
return;
}
if (((object[])parameter)[0].GetType() != typeof(string))
{
return;
}
if (((object[])parameter)[1].GetType() != typeof(int))
{
return;
}
try
{
SerialPortHandler l_spHandler = new
SerialPortHandler((string) l_params[0], (int) l_params[1]);
l_spHandler.ReadTimeout = 500;
try
{
m_dataInThreadIsRunning = true;
while (m_dataInThreadIsRunning)
{
try
{
string l_str = l_spHandler.ReadLine();
//For some reason it hangs on the row below about
10
//seconds before it enters the DataInputHandler
//I suspect this has something to do with that
OnDataInput
//is a part of the GUI thread and here I'm trying to
use it
// in a sub-thread of the GUI thread. How to solve this?
OnDataInput(this, new StringEventArgs(l_str));
}
catch (TimeoutException)
{
}
catch (InvalidOperationException)
{
}
}
}
catch (IOException)
{
m_dataInThreadIsRunning = false;
}
l_spHandler.Dispose();
}
catch (UnauthorizedAccessException e)
{
m_dataInThreadIsRunning = false;
MessageBox.Show(e.Message);
}
}
protected void DataInputHandler(object sender, EventArgs evArgs)
{
/*Some code*/
}
"Jon Skeet [C# MVP]" wrote:
Joachim wrote: It is a Windows application, and I have heard that creating threads in
Windows applications can be difficult to get right but I don't know why. How
can I use threads so that they work together with the GUI?
See http://www.pobox.com/~skeet/csharp/t...winforms.shtml
If you could post a short but complete program which demonstrates the
problem you're having, that would help. See
http://www.pobox.com/~skeet/csharp/complete.html for more information.
Jon