Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 220
user981924 Avatar asked Oct 13 '11 02:10

user981924


People also ask

Is WPF multithreaded?

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.

How many threads are there in WPF?

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.

What is multithreading C#?

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.

What is thread affinity in WPF?

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.


1 Answers

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.

like image 54
Nano Taboada Avatar answered Oct 28 '22 14:10

Nano Taboada