Software & Finance





C# WinForms - Handling Cross-thread operation





I have given a C# winforms with multi threading that can crash and how to solve the issue with cross thread operations. You need to use the Invoke function defined in Form to fix the crashing issue. Invoke function helps to match the thread id with main thead id from worker thread. Refer to the following example.


System.Threading.Thread is the class you want to use to create a thread. When you instantiate System.Threading.Thread the class you can pass two kinds of delegate.

System.Threading.ThreadStart and System.Threading.ParameterizedThreadStart


 

Here is the sample code:

 

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        public void ProcessFromThread_Crash()

        {

            //textBox1.Text = "It can crash";

            SetMyText("it is safe");

        }

 

        delegate void SetTextCallback(string text);

        public void SetMyText(string text)

        {

            if (this.textBox1.InvokeRequired)

            {

                SetTextCallback d = new SetTextCallback(SetMyText);

                this.Invoke(d, new object[] { text });

            }

            else

            {

                this.textBox1.Text = text;

            }

        }

 

       

        private void Form1_Load(object sender, EventArgs e)

        {

            System.Threading.ThreadStart threadfunction = ProcessFromThread_Crash;

 

            System.Threading.Thread myThread = new System.Threading.Thread(threadfunction);

            myThread.Start();

        }

    }

}