C# 委托 / 跨线程访问UI / 线程间操作无效: 从不是创建控件“Form1”的线程访问它...
生活随笔
收集整理的這篇文章主要介紹了
C# 委托 / 跨线程访问UI / 线程间操作无效: 从不是创建控件“Form1”的线程访问它...
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
C# 委托 / 跨線程訪問(wèn)UI / ?線程間操作無(wú)效: 從不是創(chuàng)建控件“Form1”的線程訪問(wèn)它 ?
網(wǎng)上的代碼都比較復(fù)雜,還是這個(gè)簡(jiǎn)單
見(jiàn)代碼,
?
簡(jiǎn)易解決辦法:
?
主窗體代碼
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();}));}}} }
轉(zhuǎn)載于:https://www.cnblogs.com/fxyc87/p/6546971.html
總結(jié)
以上是生活随笔為你收集整理的C# 委托 / 跨线程访问UI / 线程间操作无效: 从不是创建控件“Form1”的线程访问它...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。