打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
c#多线程更新窗口(winform)GUI的数据
1. 在.net framwork 2.0中,可以通过以下代码来实现:
1
2
3
4
5
6
7
8
9
10
11
12
private delegate void SetControlPropertyThreadSafeDelegate(Control control, string propertyName, objectpropertyValue);
public static void SetControlPropertyThreadSafe(Control control, string propertyName, object propertyValue)
{
if (control.InvokeRequired)
{
control.Invoke(new SetControlPropertyThreadSafeDelegate(SetControlPropertyThreadSafe), new object[] { control, propertyName, propertyValue });
}
else
{
control.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, control, new object[] { propertyValue });
}
}
调用方式如下:
1
2
3
// thread-safe equivalent of
// myLabel.Text = status;
SetControlPropertyThreadSafe(myLabel, "Text", status);
2.在.net 3.0或者更新的版本中,你可以重写上面的方法作为一个Control类的扩展方法,可以简化调用方式,具体代码如下:
1
myLabel.SetPropertyThreadSafe("Text", status);
在.net 3.0以上的版本完整的调用步骤如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private delegate void SetPropertyThreadSafeDelegate<TResult>(Control @this, Expression<Func<TResult>> property, TResult value);
public static void SetPropertyThreadSafe<TResult>(this Control @this, Expression<Func<TResult>> property, TResult value)
{
var propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;
if (propertyInfo == null ||
!@this.GetType().IsSubclassOf(propertyInfo.ReflectedType) ||
@this.GetType().GetProperty(propertyInfo.Name, propertyInfo.PropertyType) == null)
{
throw new ArgumentException("The lambda expression 'property' must reference a valid property on this Control.");
}
if (@this.InvokeRequired)
{
@this.Invoke(new SetPropertyThreadSafeDelegate<TResult>(SetPropertyThreadSafe), new object[] { @this, property, value });
}
else
{
@this.GetType().InvokeMember(propertyInfo.Name, BindingFlags.SetProperty, null, @this, new object[] { value });
}
}
通过使用LINQ和lambda表达式使代码更加简洁:
1
myLabel.SetPropertyThreadSafe(() => myLabel.Text, status); // status has to be a string or this will fail to compile
3.最简单的匿名方法调用:
1
2
3
4
5
6
///...blah blah updating files
string newText = "abc"; // running on worker thread
this.Invoke((MethodInvoker)delegate {
someLabel.Text = newText; // runs on UI thread
});
///...blah blah more updating files
以上方法搜集自网络,仅供参考。
转载请注明:文章转载自:[169IT-最新最全的IT资讯]
本文标题:c#多线程更新窗口(winform)GUI的数据
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
linq to entity 将多表查询返回的iqueryable对象系列化成json格式
C#中ToString(string format)扩展的妙用 - 51CTO.COM
leaflet 结合 geoserver 实现地图属性查询(附源码下载)
C#_.net core 3.0自定义读取.csv文件数据_解决首行不是标题的问题_Linqtocsv改进
IOS 遍历未知对象的属性和方法
Swift/Objc的Runtime(运行时)机制
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服