其實這個比較簡單,子線程怎么通知主線程,就是讓子線程做完了自己的事兒就去干主線程的轉回去干主線程的事兒。
那么怎么讓子線程去做主線程的事兒呢,我們只需要把主線程的方法傳遞給子線程就行了,那么傳遞方法就很簡單了委托傳值嘛;
下面有一個例子,子線程干一件事情,做完了通知主線程
public class Program
{
//定義一個為委托
public delegate void Entrust(string str);
static void Main(string[] args)
{
Entrust callback = new Entrust(CallBack); //把方法賦值給委托
Thread th = new Thread(Fun);
th.IsBackground = true;
th.Start(callback);//將委托傳遞到子線程中
Console.ReadKey();
}
private static void Fun(object obj) {
//注意:線程的參數是object類型
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("子線程循環操作第 {0} 次",i);
Thread.Sleep(500);
}
Entrust callback = obj as Entrust;//強轉為委托
callback("我是子線程,我執行完畢了,通知主線程");
//子線程的循環執行完了就執行主線程的方法
}
//主線程的方法
private static void CallBack(string str) {
Console.WriteLine(str);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
上面就是一個通過委托進行向主線程傳值(也就是通知主線程)的過程,上面我們是自己定義了一個委托,當然我們也可以使用.NET為我們提供的Action<>和Fun<>泛型委托來處理,就像這樣
public class Program
{
//定義一個為委托
public delegate void Entrust(string str);
static void Main(string[] args)
{
Action<string> callback = ((string str) => { Console.WriteLine(str); });
//Lamuda表達式
Thread th = new Thread(Fun);
th.IsBackground = true;
th.Start(callback);
Console.ReadKey();
}
private static void Fun(object obj) {
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("子線程循環操作第 {0} 次",i);
Thread.Sleep(500);
}
Action<string> callback = obj as Action<string>;
callback("我是子線程,我執行完畢了,通知主線程");
}
}
//上面的Lamuda表達式也可以回城匿名函數
//Action<string> callback = delegate(string str) { Console.WriteLine(str); };
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
下面是運行結果
————————————————
版權聲明:本文為CSDN博主「NextStand」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/NextStand/article/details/51554167
