If you use multi threading to improve the performance of your Windows Forms applications, you must make sure that you make calls to your controls in a thread-safe way.
Explore My Other Channel for More Cool and Valuable Insights
π Youtube Learn Tech Tipsπ Tiktok
π Facebook:
Access to Windows Forms controls is not inherently thread safe. If you have two or more threads manipulating the state of a control, it is possible to force the control into an inconsistent state. Other thread-related bugs are possible, such as race conditions and deadlocks. It is important to make sure that access to your controls is performed in a thread-safe way.
If you use Thread on some day, You'll see this warning
It is unsafe to call a control from a thread other than the one that created the control without using the Invoke method. The following is an example of a call that is not thread safe.
- Label name lblSetup
- Progress Bar name pbInstalling
private delegate void DelegateProgressbar(); => this function define delegate method
Demo 1: Don't have parameters
/// <summary>
/// Zidane, huuvi168@gmail.com
/// Run Control with Thread - Fix Cross Thread Problem
/// </summary>
private delegate void DelegateProgressbar();
private void RunControlWithInvoke()
{
//If the cross thread calls
if (InvokeRequired)
pbInstalling.Invoke(new DelegateProgressbar(RunControlWithInvoke), null);
else
{
pbInstalling.Style = ProgressBarStyle.Marquee;
pbInstalling.MarqueeAnimationSpeed = 30;
lblSetup.Text = "Installing ...";
}
}
private void StopControlWithInvoke()
{
//If the cross thread calls
if (InvokeRequired)
pbInstalling.Invoke(new DelegateProgressbar(StopControlWithInvoke), null);
else
{
pbInstalling.MarqueeAnimationSpeed = 0;
pbInstalling.Refresh();
lblSetup.Text = "HoΓ n TαΊ₯t";
}
}
Demo 2: With Parameters
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
Relative topic:
https://learn-tech-tips.blogspot.com/2015/11/how-to-fix-cross-thread-problem-CSharp.html
Are you interested in topic How to "fix Cross-thread problem with C#" control (1/2) from Webzone Tech Tips? If you have any thoughts or questions, please share them in the comment section below. I would love to hear from you and chat about it
Webzone Tech Tips Zidane, all things tech tips web development