700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > C# 委托 / 跨线程访问UI / 线程间操作无效: 从不是创建控件“Form1”的线程访问它...

C# 委托 / 跨线程访问UI / 线程间操作无效: 从不是创建控件“Form1”的线程访问它...

时间:2020-07-28 05:12:19

相关推荐

C# 委托 / 跨线程访问UI /  线程间操作无效: 从不是创建控件“Form1”的线程访问它...

C# 委托 / 跨线程访问UI / 线程间操作无效: 从不是创建控件“Form1”的线程访问它

网上的代码都比较复杂,还是这个简单

见代码,

简易解决办法:

主窗体代码

using System;using System.Collections.Generic;using ponentModel;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();}));}}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。