C# 委托 / 跨线程访问UI / 线程间操作无效: 从不是创建控件“Form1”的线程访问它
网上的代码都比较复杂,还是这个简单
见代码,
简易解决办法:
主窗体代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms; namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
Thread func = new Thread(lib.test_func);
func.Start(this);
}
}
}
线程代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace WindowsFormsApp1
{
public static class lib
{
public static void test_func(object frm)
{
var frm2 = frm as Form1;
while (true)
{
System.Threading.Thread.Sleep(100);
frm2.Invoke(new Action(() => {
frm2.Text = DateTime.Now.ToString();
})); }
} }
}