using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.Remoting.Messaging;

namespace ThreadMulti
{
class Program
{
delegate string MyDelegate(string msg);
static object locker=new object();

static void Main(string[] args)
{
System.Console.WriteLine("---------------------");
WriteLine("Main Thread example.", ConsoleColor.Green);
WriteLine("Async Thread example.", ConsoleColor.Red);
WriteLine("Async Thread CallBack", ConsoleColor.Cyan);
System.Console.WriteLine("---------------------\n");

WriteLine("Main Thread Begin ,ThreadId is : " + Thread.CurrentThread.ManagedThreadId, ConsoleColor.Green);
MyDelegate myDelegate = new MyDelegate(Messgae);
//异步调用,传入参数为object类型,此处用stirng示例
myDelegate.BeginInvoke("Hello Thread World!", Completed, "传参示例");
//模拟线程工作,可以看到两线程同时工作
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1000);
WriteLine("Main Thread Works!", ConsoleColor.Green);
}
WriteLine("Main Thread Complete!", ConsoleColor.Green);
Console.ReadKey();
}

static string Messgae(string msg)
{
WriteLine("Async Thread Begin ,ThreadId is : " + Thread.CurrentThread.ManagedThreadId, ConsoleColor.Red);
//模拟线程工作,可以看到两线程同时工作
for (int i = 0; i < 5; i++)
{
Thread.Sleep(500);
WriteLine("Async Thread Works!", ConsoleColor.Red);
}
WriteLine("Async Thread Complete!", ConsoleColor.Red);
return msg;
}

static void Completed(IAsyncResult iresult)
{
//通过 Thread.CurrentThread.ManagedThreadId 可以看出,回调函数运行在异步线程上
WriteLine("Async Thread CallBack Begin,ThreadId is : " + Thread.CurrentThread.ManagedThreadId, ConsoleColor.Cyan);
AsyncResult result = iresult as AsyncResult;
//使用AsyncDelegate获得委托
MyDelegate myDelegate = result.AsyncDelegate as MyDelegate;
//使用EndInvoke获取返回值
string data = myDelegate.EndInvoke(result);
//用 AsyncState 获得传入的参数(即19行“传参示例”四个字)
string asyncState = result.AsyncState.ToString();
WriteLine("返回的数据:"+data, ConsoleColor.Cyan);
WriteLine("异步调用结果状态:" + asyncState, ConsoleColor.Cyan);
//模拟回调函数工作
for (int i = 0; i < 3; i++)
{
Thread.Sleep(500);
WriteLine("Async Thread CallBack Works!", ConsoleColor.Cyan);
}
WriteLine("Async Thread CallBack Complete!", ConsoleColor.Cyan);
}


static void WriteLine(string data, ConsoleColor color)
{
lock (locker)
{
Console.ForegroundColor = color;
Console.WriteLine(data);
Console.ResetColor();
}
}
}
}


 

结果:

多线程简单示例_异步线程

 


你们的评论、反馈,及对你们有所用,是我整理材料和博文写作的最大的鼓励和唯一动力。欢迎讨论和关注!

没有整理与归纳的知识,一文不值!高度概括与梳理的知识,才是自己真正的知识与技能。 永远不要让自己的自由、好奇、充满创造力的想法被现实的框架所束缚,让创造力自由成长吧! 多花时间,关心他(她)人,正如别人所关心你的。理想的腾飞与实现,没有别人的支持与帮助,是万万不能的。