c# 子线程运行完通知主线程

来源:转载


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 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 callback = obj as Action;
callback("我是子线程,我执行完毕了,通知主线程");
}
}


分享给朋友:
您可能感兴趣的文章:
随机阅读: