C#——使用委托实现异步调用

同步调用

  • 当委托使用正常调用和多播委托正常调用的时候,都是同步调用;

异步调用

  • 使用委托的时候使用BeginInvoke(),开启线程进行异步调用;
  • BeginInvoke方法可以使用线程异步地执行委托所指向的方法。然后通过EndInvoke方法获得方法的返回值(EndInvoke方法的返回值就是被调用方法的返回值),或是确定方法已经被成功调用。
  • 使用Thread直接开启一个线程,进行异步调用
  • 使用Task

例子

“`
class Multicast
{
static void Main()
{
Student stu1 = new Student() { ID = 1, PenColor = ConsoleColor.Green };
Student stu2 = new Student() { ID = 2, PenColor = ConsoleColor.Yellow };
Student stu3 = new Student() { ID = 3, PenColor = ConsoleColor.White };
/——————使用BeginInvoke()异步调用——–/
//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异步调用--------------------
        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(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} hours.",this.ID,i);
            Thread.Sleep(1000);
        }
    }
}

“`

猜你喜欢

转载自blog.csdn.net/noEnoughChief/article/details/80669133