当前位置:网站首页>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());
}
}));
}
边栏推荐
- Summary of common skills
- Flitter imitates wechat long press pop-up copy recall paste collection and other custom customization
- Lesson 3: gcc compiler
- Xshell batch send command to multiple sessions
- Apple's tough new rule: third-party payment also requires a percentage, and developers lose a lot!
- A little awesome, 130000 a month+
- 解决C#跨线程调用窗体控件的问题
- 6、 Pinda general permission system__ pd-tools-log
- 有限元学习知识点备案
- OSPF summary
猜你喜欢
随机推荐
If Yi Lijing spits about programmers
B title: razlika priority queue approach
Shell homework the next day
2022-024arts: Longest valid bracket
2022-7-8 personal qualifying 5 competition experience (supplementary)
Two ways to monitor the change of user points
Sed job
Mycat2 deploy master-slave MariaDB
2022/7/18 exam summary
六、品达通用权限系统__pd-tools-log
Bee guitar score high octave and low octave
KV database based on raft consensus protocol
Why reserve a capacitor station on the clock output?
[GUI] swing package (window, pop-up window, label, panel, button, list, text box)
Flutter upgrade 2.10
Kotlin program control
Random distribution learning notes
Oracle 19C OCP 1z0-082 certification examination question bank (7-12)
Error handling response: Error: Syntax error, unrecognized expression: .c-container /deep/ .c-contai
File management file system based on C #