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.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 where i do something to get some raw data from a hardware.
WPF supports a single-threaded apartment model that has the following rules: One thread runs in the entire application and owns all the WPF objects. WPF elements have thread affinity, in other words other threads can't interact with each other.
WPF applications start their lives with two threads: one for rendering and another for the UI. The rendering thread runs hidden in the background while the UI thread receives input, handles events, paints the screen, and runs application code. The UI thread queues work items inside an object called a Dispatcher.
Multi-threading is a process that contains multiple threads within a single process. Here each thread performs different activities. For example, we have a class and this call contains two different methods, now using multithreading each method is executed by a separate thread.
So thread affinity means that the thread, in this case the UI thread that instantiates an object is the only thread that can access its members. So for example, dependency object in WPF has thread affinity.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With