C# 委托 / 跨線程訪問UI / 線程間操作無效: 從不是創(chuàng)建控件“Form1”的線程訪問它
網(wǎng)上的代碼都比較復雜,還是這個簡單
見代碼,
簡易解決辦法:
主窗體代碼
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();
}));
}
}
}
}
浙公網(wǎng)安備 33010602011771號