被线程弄迷糊了,自己做个笔记,我想让主线程不受影响的情况下,在新开的线程中执行,并给返回结果,结果不是很满意,主线程还是不动。以后再解决
//定义方法,带参数的
private string ThreadRun(string p_num) { int i = 0; int.TryParse(textBox1.Text, out i); string v_str = ""; for (int j = 1; j <= i; j++) { v_str = j.ToString() + "\r\n" + v_str; } return v_str; } //定义委托,带参数的 private delegate string MyInvokeDelegate(string p_num); private void button2_Click(object sender, EventArgs e) { string p_num = textBox1.Text; //赋值 MyInvokeDelegate task = new MyInvokeDelegate(ThreadRun); //申明委托 //使用BeginInvoke方法异步调用newTask方法,并传入p_num 作为newTask的参数 IAsyncResult asyncResult = task.BeginInvoke(p_num,null, null); // EndInvoke方法将被阻塞2秒 // EndInvoke方法接收一个IAsyncResult的参数,将返回newTask方法的返回值 string result = task.EndInvoke(asyncResult); MsgForm f = new MsgForm(result); f.Show(); // DoWork(); }
下面是引用别人的内容,很有用。
1. new Thread()
新开一个线程,执行一个方法,没有参数传递:
private void DoWork() { Thread t = new Thread(new ThreadStart(this.DoSomething)); t.Start(); } private void DoSomething() { MessageBox.Show("thread start"); }
新开一个线程,执行一个方法,并传递参数:
private void DoWork() { Thread t = new Thread(new ParameterizedThreadStart(this.DoSomething)); t.Start("guozhijian"); } private void DoSomething(object o) { MessageBox.Show(o.ToString()); }
参数定义为object类型。
2. ThreadPool
众所周知,新开一个线程代价是很高昂的,如果我们每个操作都新开一个线程,那么太浪费了,于是,下面使用线程池。
无参数传递:
private void DoWork() { ThreadPool.QueueUserWorkItem(new WaitCallback(this.DoSomething)); } private void DoSomething(object o) { MessageBox.Show("thread start"); }
有参数传递:
private void DoWork() { ThreadPool.QueueUserWorkItem(new WaitCallback(this.DoSomething), "guozhijian"); } private void DoSomething(object o) { MessageBox.Show(o.ToString()); }
使用匿名方法更灵活:
private void DoWork() { string name = "guozhijian"; ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object o){ MessageBox.Show(name); })); }
在匿名代码段里面可以直接访问局部变量,不用在关心参数传递的问题
二. Invoke
1. this.Invoke
现在,在业务线程里面执行完毕,要改变窗体控件的值了,此时,如果直接通过this得到控件的句柄,然后对它进行操作是会抛异常的,.Net WinForm Application里面是不允许这样的操作的。这是,可以调用Invoke方法
2.Invoke方法签名:
object Control.Invoke(Delegate Method)
object Control.Invoke(Delegate Method, params object[] args)
3.使用自定义委托
private void DoWork() { WaitCallback wc = new WaitCallback(this.DoSomething); ThreadPool.QueueUserWorkItem(wc, "Guozhijian"); } private delegate void MyInvokeDelegate(string name); private void DoSomething(object o) { this.Invoke(new MyInvokeDelegate(this.ChangeText), o.ToString()); } private void ChangeText(string name) { this.textBox1.Text = name; }
哦,太麻烦了,难道我每次都要定义一个委托啊,这样可不行。
4.使用System.Action:
private void DoWork() { WaitCallback wc = new WaitCallback(this.DoSomething); ThreadPool.QueueUserWorkItem(wc, "Guozhijian"); } private void DoSomething(object o) { this.Invoke(new Action<string>(this.ChangeText), o.ToString()); } private void ChangeText(string name) { this.textBox1.Text = name; }
本例传递一个参数,System.Action有很多个重载,可以无参数(非泛型),而最多可以有四个参数,同样采用匿名方法,不使用泛型形式的System.Action,如下:
private void DoWork() { WaitCallback wc = new WaitCallback(this.DoSomething); ThreadPool.QueueUserWorkItem(wc, "Guozhijian"); } private void DoSomething(object o) { this.Invoke(new Action(delegate() { this.textBox1.Text = o.ToString(); })); }
5.使用System.Func
如果Invoke调用主窗体操作之后,还希望在调用完得到一个返回值:
private void DoWork() { WaitCallback wc = new WaitCallback(this.DoSomething); ThreadPool.QueueUserWorkItem(wc, "Guozhijian"); } private void DoSomething(object o) { System.Func<string, int> f = new Func<string, int>(this.GetId); object result = this.Invoke(f,o.ToString()); MessageBox.Show(result.ToString()); } private int GetId(string name) { this.textBox1.Text = name; if (name == "Guozhijian") { return 999; } else { return 0; } }
result的值为 999。
System.Func同样有很多泛形重载,这里不赘述。
6.关于Invoke的拥有者:Control
本文例中都是用this来引用,这里this替换为窗体任何一个控件的句柄都是OK的,因为Control.Invoke含义是将方法委托给拥有该Control的线程去执行。
---------------------------------------------------------------
一、什么时候使用多线程 对于需要等待的操作如:文件操作、从网络加载信息等,此时可以使用一个线程进行这些操作,新开一个线程运行其他的操作,提高效率增加用户体验。典型的例子是word程序中的拼写检查器:一个线程等待用户输入,另一个线程进行后台搜索、第三个线程将写入的数据存储在临时文件中、第四个线程进行从internet上下载相关信息。 二、c#使用线程的最简单方法——异步委托 C#使用线程的方法很多其中使用委托(Delegate)的BeginEnvoke()方法和EndInvoke()是一个简单的方法。 使用BeginInvoke方法步骤: 1.创建一个要执行的函数如以下代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace MyThread { class Program { //创建函数 private static int newTask(int ms) { Console.WriteLine("任务开始"); Thread.Sleep(ms); Random random = new Random(); int n = random.Next(10000); Console.WriteLine("任务完成"); return n; } static void Main(string[] args) { } } } 创建了一个返回类型为int的newTask函数,该函数接收一个int型的参数,指定线程的阻塞时间。 2.创建一个可以指向该方法的委托,即委托的参数类型和返回类型与该函数一致,如下代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace MyThread { class Program { //创建函数 private static int newTask(int ms) { Console.WriteLine("任务开始"); Thread.Sleep(ms); Random random = new Random(); int n = random.Next(10000); Console.WriteLine("任务完成"); return n; } //创建委托 private delegate int NewTaskDelegate(int ms); static void Main(string[] args) { } } } 3.实例化新创建的委托,并使用该实例的BeginInvoke方法和EndInvoke方法进行函数的异步调用。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace MyThread { class Program { //创建函数 private static int newTask(int ms) { Console.WriteLine("任务开始"); Thread.Sleep(ms); Random random = new Random(); int n = random.Next(10000); Console.WriteLine("任务完成"); return n; } //创建委托 private delegate int NewTaskDelegate(int ms); static void Main(string[] args) { //实例化委托 NewTaskDelegate task = newTask; //使用BeginInvoke方法异步调用newTask方法,并传入2000作为newTask的参数 IAsyncResult asyncResult = task.BeginInvoke(2000, null, null); // EndInvoke方法将被阻塞2秒 // EndInvoke方法接收一个IAsyncResult的参数,将返回newTask方法的返回值 int result = task.EndInvoke(asyncResult); Console.WriteLine(result); } } } 关于BeginInvoke的参数和返回值: 它与您需要异步执行的方法具有相同的参数,另外它还有两个可选参数。第一个参数是一个 AsyncCallback 委托,该委托引用在异步调用完成时要调用的方法。第二个参数是一个用户定义的对象,该对象可向回调方法传递信息。BeginInvoke 立即返回,不等待异步调用完成。BeginInvoke 会返回 IAsyncResult,这个结果可用于监视异步调用进度。 关于EndInvoke的返回值:EndInvoke方法的返回值就是被调用方法的返回值。如果异步调用的方法(这里指newTask方法)尚未完成,EndInvoke 将一直阻止调用线程,直到异步调用异步调用的方法(这里指newTask方法)完成后,才允许调用线程执行。