C# 委托 / 跨线程访问UI / 线程间操作无效: 从不是创建控件“Form1”的线程访问它...
生活随笔
收集整理的這篇文章主要介紹了
C# 委托 / 跨线程访问UI / 线程间操作无效: 从不是创建控件“Form1”的线程访问它...
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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();}));}}} }
轉載于:https://www.cnblogs.com/fxyc87/p/6546971.html
總結
以上是生活随笔為你收集整理的C# 委托 / 跨线程访问UI / 线程间操作无效: 从不是创建控件“Form1”的线程访问它...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ace admin
- 下一篇: 5款Java微服务开源框架