码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-03-14 10:30:31      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:read   csharp   text   无效   initial   sha   art   threading   draw   

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();
				}));

			}
		}

	}
}

  

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

标签:read   csharp   text   无效   initial   sha   art   threading   draw   

原文地址:http://www.cnblogs.com/fxyc87/p/6546971.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!