首页 / C# / 委托、异步调用、同步调用详解(C#)
委托、异步调用、同步调用详解(C#)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了委托、异步调用、同步调用详解(C#),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1666字,纯文字阅读大概需要3分钟。
内容图文
namespace MyTest_MultiThread
{
class Program
{
static void Main(string[] args)
{
Student stu1 = new Student() { ID = 1, PenColor = ConsoleColor.Yellow };
Student stu2 = new Student() { ID = 2, PenColor = ConsoleColor.Green };
Student stu3 = new Student() { ID = 3, PenColor = ConsoleColor.Red };
/*
//(同步调用:你做完了,我开始做,单线程)
Action action1 = new Action(stu1.DoHomeWork);
Action action2 = new Action(stu2.DoHomeWork);
Action action3 = new Action(stu3.DoHomeWork);
action1 += action2;
action1 += action3;
action1.Invoke(); //多波委托
*/
/*
//(异步调用:我们一起开始做,多线程)
Action action1 = new Action(stu1.DoHomeWork);
Action action2 = new Action(stu2.DoHomeWork);
Action action3 = new Action(stu3.DoHomeWork);
action1.BeginInvoke(null,null);
action2.BeginInvoke(null, null);
action3.BeginInvoke(null, null);
*/
/*
//异步调用:Thread
Thread thread1 = new Thread(new ThreadStart(stu1.DoHomeWork));
Thread thread2 = new Thread(new ThreadStart(stu2.DoHomeWork));
Thread thread3 = new Thread(new ThreadStart(stu3.DoHomeWork));
thread1.Start();
thread2.Start();
thread3.Start();
*/
Task task1 = new Task(new Action(stu1.DoHomeWork));
Task task2 = new Task(new Action(stu2.DoHomeWork));
Task task3 = new Task(new Action(stu3.DoHomeWork));
task1.Start();
task2.Start();
task3.Start();
for (int i = 0; i < 10; i++)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Main thread {0}",i);
Thread.Sleep(1000);
}
}
}
class Student
{
public int ID { get; set; }
public ConsoleColor PenColor { get; set; }
public void DoHomeWork()
{
for (int i = 0; i < 5; i++)
{
Console.ForegroundColor = this.PenColor;
Console.WriteLine("Student {0} doing homework {1} hour(s).", this.ID, i);
Thread.Sleep(1000);
}
}
}
}
内容总结
以上是互联网集市为您收集整理的委托、异步调用、同步调用详解(C#)全部内容,希望文章能够帮你解决委托、异步调用、同步调用详解(C#)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。