Winform 让跨线程访问变得更简单

时间:2023-03-09 07:17:03
Winform 让跨线程访问变得更简单

Winform 让跨线程访问变得更简单

前言

  由于多线程可能导致对控件访问的不一致,导致出现问题。C#中默认是要线程安全的,即在访问控件时需要首先判断是否跨线程,如果是跨线程的直接访问,在运行时会抛出异常。近期在项目中碰到这个问题,首先想到的是,关闭跨线程检查,因为做的Winform没有多么复杂,图省事就直接这样做了,之后又出了一点点问题,还是必需通过委托的方式来实现。

资源下载

  测试示例

解决跨线程访问:

  网上的资料很多,这里直接摘抄。

  1、关闭跨线程检查。

  2、通过委托的方式,在控件的线程上执行。

  具体的代码如下:

Winform 让跨线程访问变得更简单
using System;
using System.Threading;
using System.Windows.Forms; namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
//方法一:不进行跨线程安全检查
CheckForIllegalCrossThreadCalls = false;
} private void button1_Click(object sender, EventArgs e)
{
Thread th1 = new Thread(new ThreadStart(CalNum));
th1.Start();
} private void CalNum()
{
SetCalResult(DateTime.Now.Second);
} //方法二:检查是否跨线程,然后将方法加入委托,调用委托
public delegate void SetTextHandler(int result);
private void SetCalResult(int result)
{
if (label2.InvokeRequired == true)
{
SetTextHandler set = new SetTextHandler(SetCalResult);//委托的方法参数应和SetCalResult一致
label2.Invoke(set, new object[] { result }); //此方法第二参数用于传入方法,代替形参result
}
else
{
label2.Text = result.ToString();
}
}
}
}
Winform 让跨线程访问变得更简单

改进

  在我的Winform程序中,子线程涉及到对多个控件的更改,于是封装了一下,我这里使用的是拓展方法,只有在.net 3.5上才能支持,如果是.net2.0的环境,需要添加

namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
public class ExtensionAttribute : Attribute { }
}

  封装如下:

Winform 让跨线程访问变得更简单
using System.Threading;
using System.Windows.Forms; namespace WindowsFormsApplication1
{
public static class Class1
{
/// <summary>
/// 跨线程访问控件 在控件上执行委托
/// </summary>
/// <param name="ctl">控件</param>
/// <param name="del">执行的委托</param>
public static void CrossThreadCalls(this Control ctl, ThreadStart del)
{
if (del == null) return;
if (ctl.InvokeRequired)
ctl.Invoke(del, null);
else
del();
}
}
}
Winform 让跨线程访问变得更简单

  具体的测试如下:

Winform 让跨线程访问变得更简单
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms; namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
var th = new Thread(() =>
{
//label1.Enabled = false;
label1.CrossThreadCalls(() => { label1.Enabled = !label1.Enabled; });
WriteMessage(DateTime.Now.ToString());
});
th.IsBackground = true;
th.Start();
} public void WriteMessage(string msg)
{
label1.CrossThreadCalls(() =>
{
label1.Text = msg;
});
}
}
}
Winform 让跨线程访问变得更简单

  这样一行代码就可以完成跨线程访问啦。

  Winform 让跨线程访问变得更简单