c# 子线程运行完通知主线程
程序员文章站
2022-06-10 20:34:25
...
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)
{
for (int i = 0; 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);
}
}
上面就是通过委托向主线程传值(也就是通知主线程)的过程,也可以用.NET为我们提供的泛型委托来处理
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("我是子线程,我执行完毕了,通知主线程");
}
}
上一篇: C# 在数组中判断是否存在某个数组值
下一篇: 子界面传值到父界面不刷新修改table