WPF threading C#
I'm very new to threading. I hope someone can give me some example.
I'm trying to start a thread when user click on start button and do the following process:
private void btnStart_Click(object sender, RoutedEventArgs e)
{
if (serialPort.IsOpen)
serialPort.Close();
try
{
//To set all the parameters for Serial Comm
serialPort.PortName = "COM14";
serialPort.BaudRate = int.Parse("38400");
serialPort.Parity = Parity.None;
serialPort.Data开发者_StackOverflow社区Bits = 8;
serialPort.StopBits = StopBits.One;
serialPort.Encoding = System.Text.Encoding.ASCII;
serialPort.DataReceived += new SerialDataReceivedEventHandler(GotRawData);
serialPort.Open();
//To show that Com Port is Opened
txtboxOutput.AppendText(DateTime.Now.ToString("hh:mm:ss tt") + " - COM14 is opened." + Environment.NewLine);
txtboxOutput.ScrollToEnd();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void GotRawData() is a method where i do something to get some raw data from a hardware.
You might find the System.ComponentModel.BackgroundWorker class rather useful which in my understanding is the simplest way to execute an operation on a separate thread.
I do not know if I understood the question correctly. Once the user clicks a button, you want to start a seperate thread and receive data from the serial port there. I think this should that:
private void btnStart_Click(object sender, RoutedEventArgs e)
{
Thread GetData = new Thread(thFunctionToRun);
GetData.Start();
}
You're not making any blocking calls in btnStart_Click
, so it's fine to just run this on the main UI thread.
A couple of points:
Remember that
GotRawData
will be called on a worker thread, so if you are accessing any UI controls, you will have to marshal those calls back onto the UI thread.From MSDN SerialPort.Open :
The best practice for any application is to wait for some amount of time after calling the Close method before attempting to call the Open method, as the port may not be closed instantly.
精彩评论