C#-WinForm跨线程修改UI界面的示例
作者:UP技术控 时间:2022-01-14 13:25:44
背景
在我做WinForm开发的过程中,经常会遇到耗时操作或阻塞操作。他们会引发软件的卡顿甚至假死,严重影响软件的使用。因此,这类耗时或阻塞的操作一般都会使用异步的方式去执行,不影响主线程(UI线程)与用户间的交互。但多个线程竞争读写同一个资源往往会造成意想不到的意外结果,UI界面也是一种资源,所以跨线程修改UI界面往往被加以限制。而在Winform中,跨线程修改UI界面同样是不被允许的。在子线程中修改界面控件时Visual Studio会报出如下错误:
解决思路
.Net提供了很多跨线程修改UI的方法,每种方法也有与之对应的工具类。我最常用的方法是ThreadPool+ delegate的方式完成跨线程对UI对的修改。
实例代码
1、定义委托,把内容写在控件里面
private delegate void SetLabelDelegate(string value);
private delegate void SetLabelDelegate2(string value);
private void SetText(string value)
{
if (this.InvokeRequired)
{
SetLabelDelegate d = new SetLabelDelegate(SetText);
this.Invoke(d, new object[] { value });
}
else
{
txtbigcrmresult.Text = value.ToString() + txtbigcrmresult.Text;
}
}
2、定义方法,线程调用
private void button3_Click(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(dao), "test");
}
private void dao(object url)
{
IDbConnection conn = new SqlConnection(txtbigcrmui.Text);
SetText("\r\n" + "start");
.........................
SetText("\r\n" + "end");
}
3、更新ui控件
SetText("\r\n" + "start");
总结
1、使用delegate实现跨线程更新UI;
2、使用ThreadPool实现多线程执行方法,避免卡顿;
来源:https://www.cnblogs.com/lyl6796910/archive/2021/01/04/14228776.html
标签:c#,winform,跨线程,修改界面
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java 使用idea将工程打成jar并创建成exe文件类型执行的方法详解
2022-12-07 02:49:30
![](https://img.aspxhome.com/file/2023/2/60702_0s.png)
解决javac不是内部或外部命令,也不是可运行程序的报错问题
2022-07-13 22:39:25
![](https://img.aspxhome.com/file/2023/3/66623_0s.jpg)
Java客户端调用.NET的WebService实例
2023-11-03 17:22:00
![](https://img.aspxhome.com/file/2023/8/58988_0s.png)
Java序列化和反序列化示例介绍
2023-11-25 04:24:26
Java新手环境搭建 Tomcat安装配置教程
2021-08-19 08:06:23
![](https://img.aspxhome.com/file/2023/4/61294_0s.jpg)
Java 实战项目锤炼之医院门诊收费管理系统的实现流程
2022-08-10 11:35:08
![](https://img.aspxhome.com/file/2023/0/74990_0s.png)
详解java中float与double的区别
2021-09-12 11:04:47
java操作json对象出现StackOverflow错误的问题及解决
2023-03-04 20:06:14
![](https://img.aspxhome.com/file/2023/2/63162_0s.png)
Mybatis如何获取最新插入数据的id
2023-02-26 08:15:20
C#接口归纳总结实例详解
2021-08-18 16:55:54
Mybatis配置之<typeAliases>别名配置元素解析
2023-08-02 03:09:54
![](https://img.aspxhome.com/file/2023/7/60447_0s.png)
mybatis中使用oracle关键字出错的解决方法
2022-05-14 10:19:23
java.net.ConnectException: Connection refused问题解决办法
2023-11-28 18:49:52
Mybatis-Plus注入SQL原理分析
2022-11-09 21:17:22
![](https://img.aspxhome.com/file/2023/6/64496_0s.jpg)
postman测试传入List<String>参数方式
2022-10-13 01:34:40
![](https://img.aspxhome.com/file/2023/2/66982_0s.png)
教你用Java GUI实现文本文件的读写
2023-05-25 06:47:13
![](https://img.aspxhome.com/file/2023/3/66483_0s.png)
Java实现远程控制技术完整源代码分享
2022-04-10 20:31:53
![](https://img.aspxhome.com/file/2023/3/68003_0s.jpg)
Spark SQL关于性能调优选项详解
2021-11-05 22:32:56
Java多个版本切换的几种方法
2022-04-22 14:10:15
![](https://img.aspxhome.com/file/2023/8/63108_0s.png)
配置Ant执行Jmeter脚本过程详解
2023-11-09 22:35:29
![](https://img.aspxhome.com/file/2023/5/65645_0s.png)