WPF threading c #

I am very new to streaming. Hope someone can give me an example.

I try to start a thread when the user clicks the start button and performs 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.DataBits = 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 in which I do something to get raw data from hardware.

+6
source share
3 answers

You can find the System.ComponentModel.BackgroundWorker class, which, in my opinion, is the easiest way to perform an operation on a separate thread.

+7
source

I don’t know if I understood the question correctly. As soon as the user clicks the button, you want to start a separate stream and receive data from the serial port. I think this should:

 private void btnStart_Click(object sender, RoutedEventArgs e) { Thread GetData = new Thread(thFunctionToRun); GetData.Start(); } 
0
source

You do not make any blocking calls in btnStart_Click , so just launch it in the main user interface thread.

A few points:

  • Remember that GotRawData will be called in the GotRawData , so if you access any UI controls, you will have to march these callbacks to the UI thread.

  • From MSDN SerialPort.Open :

The best practice for any application is to wait a while after calling the Close method before trying to call the Open method, since the port cannot be closed immediately.

0
source

Source: https://habr.com/ru/post/899182/


All Articles