当前位置:网站首页>Solve the problem of C # calling form controls across threads
Solve the problem of C # calling form controls across threads
2022-07-26 08:36:00 【luobeihai】
Have a problem
In use C# When writing a form application , When debugging, an error is suddenly reported , Say my thread operation is invalid , Not from the thread that created the control to access the control .
The reason for this problem is :
C# Only the main thread can access the control .
from .NET Framework 2.0 Class library start ,.net The framework is for winform In this paper, we use multithreading to call the form control for security detection , That is to say, if I call the form control from another thread that is not the main thread , There will be an exception .
resolvent
There are many ways to solve cross thread calls , Here are two .
1. Turn off the security check of cross thread access control directly
Turn off security checks , We just need to add the following code to the form function :
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false; // This code turns off the security check
}
This method is the simplest , It directly turns off the security check of cross thread access control , Then you can allow you to randomly change the properties of the control in other sub threads , Such access is uncontrollable , So this method is not recommended .
2. Call... Through a delegate
C# Delegate call of , similar C The function pointer in the language is the same as the function parameter .
C# Provides delegate and invoke To call the control from other threads .
The simplified method of use is as follows , It is directly in the part of code that needs cross thread access to controls , Written in delegate Just enclose the inside .
this.Invoke(new EventHandler (delegate
{
// This is the code related to the access control
label1.Text = "hello";
}));
such as , I met it at the beginning , I am in a thread of network data receiving , Write the received data into the received text box , No addition Invoke That would be wrong , If you add it, you won't , The following code :
private void ReceiveCallback(IAsyncResult AR)
{
// Check how much bytes are recieved and call EndRecieve to finalize handshake
this.Invoke(new EventHandler(delegate
{
try
{
int recieved = tcpClient.EndReceive(AR);
if (recieved <= 0)
return;
string message = Encoding.GetEncoding("GBK").GetString(recieveBuffer, 0, recieved); // Only convert the received data
// Here is cross thread access tbRecv Text box control , This is actually to add the received data to the text box to display
tbRecv.AppendText($"[{
DateTime.Now.ToString("yyy-MM-dd HH.mm.ss.fff")}] {
message}\r\n");
// Start receiving again
tcpClient.BeginReceive(recieveBuffer, 0, recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (SocketException ex)
{
MessageBox.Show(ex.ToString());
}
}));
}
边栏推荐
- 22-07-16 personal training match 3 competition experience
- Kotlin data type
- BGP routing principle
- 2022/7/18 exam summary
- Oracle 19C OCP certification examination software list
- Excel find duplicate lines
- 2022-024arts: Longest valid bracket
- Analysis on the query method and efficiency of Oracle about date type
- Date and time function of MySQL function summary
- Flutter compilation fails
猜你喜欢

Flitter imitates wechat long press pop-up copy recall paste collection and other custom customization

A little awesome, 130000 a month+

On some concepts involved in journal papers compilation + journal query methods

Nodejs2day(nodejs的模块化,npm下载包,模块加载机制)

Kotlin data type

Winter vacation homework & Stamp cutting

Apple's tough new rule: third-party payment also requires a percentage, and developers lose a lot!

KV database based on raft consensus protocol

2022-7-9 personal qualifying 6 competition experience

基于C语言实现的人机交互软件
随机推荐
Flutter WebView jitter
Bee guitar score high octave and low octave
Using the primitive root of module m to judge and solve
23.9 application exit application exit
Fluent custom popupmenubutton
Seq2seq and attention model learning notes
解决C#跨线程调用窗体控件的问题
[endnote] compilation of document types and abbreviations of document types
Mysql/mariadb (Galera multi master mode) cluster construction
Oracle 19C OCP 1z0-082 certification examination question bank (19-23)
The second lesson is the construction of development environment
Random distribution learning notes
Maximum common substring & regularity problem
Spark scheduling analysis
Status management bloc provider geTx
Flutter text is left aligned with no blank space in the middle
监控用户积分变化的两种方式
【FreeSwitch开发实践】使用SIP客户端Yate连接FreeSwitch进行VoIP通话
【搜索专题】看完必会的搜索问题之洪水覆盖
Nodejs2day(nodejs的模块化,npm下载包,模块加载机制)