C#中worker线程与UI主线程通信

来源:互联网 发布:软件测试 前景 编辑:程序博客网 时间:2024/05/29 14:40
1. delegate(委托)
    这个就类似C++中的函数指针的概念
2. Invoke
     在worker线程中使用System.Windows.Forms.Control 的Invoke方法, 就可以与UI主线程进行通信
3. C#中向线程传递数据只有两种方法(<<Professional Csharp 2008的19.3.1给线程传送数据>>:
     1) ParameterizedThreadStart
     2)定制类
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Net;using System.IO;using System.Threading;namespace Test{    public partial class main : Form    {        public main()        {            InitializeComponent();            fun = Function;        }        private void button1_Click(object sender, EventArgs e)        {            Thread t1 = new Thread(MyThread);            t1.Start(this);        }        private delegate void FunctionDelegate(string message);        private void Function(string message)        {            this.textBox1.Text = message;        }        private FunctionDelegate fun;        private void  MyThread(object o)        {           main UI = (main)o;            UI.Invoke(UI.fun,new Object[] {"KKKKKKKKKKKKK"});        }    }}


原创粉丝点击