C# 代理的异步特性(Asynchronous Nature of Delegates)

2023-10-16 23:38

本文主要是介绍C# 代理的异步特性(Asynchronous Nature of Delegates),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

http://www.penna.cn/blog/?p=127

 

  

 

 

 

原文:http://www.c-sharpcorner.com/UploadFile/Ashush/AsyncDelegates03032008144119PM/AsyncDelegates.aspx

作者:Amr Ashush

翻译:Penna

本文介绍了如何利用代理类型来实现异步调用,向您展示代理类型的另一面。

引言

.Net中构建多线程应用程序有以下几种方法:

1、使用代理(delegates)进行异步调用

2、使用BackgroundWorker组件

3、使用Thread

本文只涉及异步代理调用,如果您想了解另外两种方法,请参阅作者的相关文章:

Using the BackgroundWorker component

Building a multithreaded application using Thread calss

这里假设您已经足够了解代理类型,否则,请移步:

Delegates in C#

异步代理调用(Asynchronous delegates calls

先来看看一般的代理调用,在应用程序中通过代理来指向一个方法,供后面调用:

示例 1:

namespace DelegateSynchronousCalls
{
    public delegate int MyDelegate(int x);
    public class MyClass
    {
        //A method to be invoke by the delegate
        public int MyMethod(int x)
        {
            return x * x;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //invoke the method synchronously

            int result = del(5);
            //this text will not show till the first operation finish
            Console.WriteLine("Proccessing operation…");
            Console.WriteLine("Result is: {0}", result);
            Console.ReadLine();
        }
    }
}

您可以看到,我们在main线程中使用代理(del)来调用 一个方法(myClass1.MyMethod),如果这个方法是一个较长的进程,例如:

public int MyMethod(int x)
{
    //simulate a long running proccess
    Thread.Sleep(10000);
    return x*x;   
}

这个操作将会持续十秒钟,在这个过程中整个程序将没有响应,并且不能进行其他操作,只能等待这个方法调用结束。

那么如何解决这个问题呢?呵呵,自然是使用代理进行异步调用了 ,如何实现?请看下面的例子:

示例2

namespace
DelegatesAsynchronousCalls

{
    class Program

    {
        public delegate int MyDelegate(int x);

        public class MyClass
        {
            //A method to be invoke by the delegate
            public int MyMethod(int x)
           {
                //simulate a long running proccess
                Thread.Sleep(10000);
                return x * x;
            }
        }

        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our method in another thread
            IAsyncResult async = del.BeginInvoke(5, null, null);

            //do something while MyMethod is executing.

            Console.WriteLine("Proccessing operation…");

            //recieve the results.
            int result = del.EndInvoke(async);
            Console.WriteLine("Result is: {0}", result);
            Console.ReadLine();
        }
    }
}

  您可以看到,我们像往常一样定了一个代理,但却没有直接通过它来调用方法,而是调用代理的BeginInvoke()方法,该方法返回一个IAsyncResult对象,然后把这个对象提交给代理的EndInvoke()方法,最终由EndInvoke()来提供返回值。(复杂吧!!??)『译者注:还好 

  这时您会问,这些方法都是哪来的?答案很简单,当您定义一个代理时,一个特定的(custom)代理类将生成并添加到你的程序集当中。这个类包含很多方法,像Invoke(),BeginInvoke()EndInvoke()

>等。当您使用代理调用一个方法是,实际上是调用了代理类的Invoke()方法,Invoke()方法在主线程中同步执行你指定的方法,如示例1。而异步调用某一方法(underlying method)时,您首先调用BeginInvoke(),此时您的方法将被加入另一线程的队列中等待执行。 BeginInvoke()并不返回您指定方法的返回值,而是返回一个IAsyncResult对象,可在异步操作完成时访问它。要获得执行结果,把IAsyncResult传给代理的EndInvoke()方法, EndInvoke()等待异步操作完成,然后返回执行结果。

  您可能会问,BeginInvoke()方法的另外两个参数是干啥的?另外两个参数,第一个是用来传递回调方法(callback),另一个是一个状态对象。若您不需要这些选项,只要传空值(null)就可以了。下面来看看如何使用它们。

使用AsyncCallback delegate

  让调用进程知道异步操作是否已经完成,可以有两种方式,第一个是使用IAsyncResult接口的IsCompleted属性。在调用EndInvoke()之前,调用线程可以通过这个属性来判断异步操作是否完成,若未完成IsCompleted返回false。若IsComplete返回true,调用线程就可以获取结果了。

示例 3

namespace
DelegatesAsyncCallsIsCompleted

{

    public delegate int MyDelegate(int x);

    public class MyClass

    {
        //A method to be invoke by the delegate

        public int MyMethod(int x)
        {
            //simulate a long running proccess
            Thread.Sleep(3000);
            return x * x;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our methe in another thread
            IAsyncResult async = del.BeginInvoke(5, null, null);

            //loop until the method is complete
            while (!async.IsCompleted)
            {
                Console.WriteLine("Not Completed");
            }

            int result = del.EndInvoke(async);
            Console.WriteLine("Result is: {0}", result);
            Console.ReadLine();

        }
    }

}


如果用一个代理来告知调用进程异步操作已经完成,效果会更好。为此,您必须向BeginInvoke()方法提供一个AsyncCallback代理的实例作为参数,这个代理会在异步操作完成时自动调用指定的方法。
这个指定的方法必须含有一个唯一的IAsyncResult类型的参数,并且没有返回值(返回void)。

public
static void MyCallBack(IAsyncResult async)

{

}

这个IAsyncResult对象和您调用BeginInvoke() 方法是返回的是同一个对象。

示例4

namespace
AsyncCallbackDelegate

{
    public delegate int MyDelegate(int x);
    public class MyClass
    {
        //A method to be invoke by the delegate
        public int MyMethod(int x)
        {
            //simulate a long running proccess
            Thread.Sleep(10000);
            return x * x;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our methe in another thread
            IAsyncResult async = del.BeginInvoke(5, new AsyncCallback(MyCallBack), null);
            Console.WriteLine("Proccessing the Operation….");
            Console.ReadLine();
        }

        static void MyCallBack(IAsyncResult async)
        {
            Console.WriteLine("Operation Complete);
        }

    }
}

  记住,MyCallback()在MyMethod()方法完成时将由AsyncCallback调用。
  您可以看到,我们并没有调用EndInvoke(),因为MyCallback()方法没有访问MyDelegate对象,因此,我们可以将传入的IAsyncResult参数转换为AsyncResult类型,然后使用静态的AsyncDelegate属性来引用由其他地方生成的原始异步代理。

我们可以重写MyCallback()方法,如下所示:

static
void MyCallBack(IAsyncResult async)

{

    AsyncResult ar = (AsyncResult)async;

    MyDelegate del = (MyDelegate)ar.AsyncDelegate;

    int x = del.EndInvoke(async);

    Consol.WriteLine("Operation Complete, Result is: {0}", x);

}

BeginInvoke()方法的最后一个参数用来传递附加的状态信息给主线程的回调方法。这是参数是System.Object类型的,所以您可以传递任何类型的信息。

示例 5

namespace AsyncCallbackDelegate
{
    public delegate int MyDelegate(int x);
    public class MyClass
    {
        //A method to be invoke by the delegate
        public int MyMethod(int x)
        {
            //simulate a long running proccess
            Thread.Sleep(10000);
            return x * x;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our methe in another thread
            IAsyncResult async = del.BeginInvoke(5, new AsyncCallback(MyCallBack), "A message from the main thread");
            Console.WriteLine("Proccessing the Operation….");
            Console.ReadLine();
        }

        static void MyCallBack(IAsyncResult async)
        {
            AsyncResult ar = (AsyncResult)async;
            MyDelegate del = (MyDelegate)ar.AsyncDelegate;
            int x = del.EndInvoke(async);
 
            //make use of the state object.
            string msg = (string)async.AsyncState;
            Console.WriteLine("{0}, Result is: {1}", msg, x);
        }
    }
}

希望本文对您理解代理的异步特性有所帮助。

这篇关于C# 代理的异步特性(Asynchronous Nature of Delegates)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/221507

相关文章

C#中checked关键字的使用小结

《C#中checked关键字的使用小结》本文主要介绍了C#中checked关键字的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录✅ 为什么需要checked? 问题:整数溢出是“静默China编程”的(默认)checked的三种用

C#中预处理器指令的使用小结

《C#中预处理器指令的使用小结》本文主要介绍了C#中预处理器指令的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录 第 1 名:#if/#else/#elif/#endif✅用途:条件编译(绝对最常用!) 典型场景: 示例

C#实现将XML数据自动化地写入Excel文件

《C#实现将XML数据自动化地写入Excel文件》在现代企业级应用中,数据处理与报表生成是核心环节,本文将深入探讨如何利用C#和一款优秀的库,将XML数据自动化地写入Excel文件,有需要的小伙伴可以... 目录理解XML数据结构与Excel的对应关系引入高效工具:使用Spire.XLS for .NETC

C#如何在Excel文档中获取分页信息

《C#如何在Excel文档中获取分页信息》在日常工作中,我们经常需要处理大量的Excel数据,本文将深入探讨如何利用Spire.XLSfor.NET,高效准确地获取Excel文档中的分页信息,包括水平... 目录理解Excel中的分页机制借助 Spire.XLS for .NET 获取分页信息为什么选择 S

C#高效实现在Word文档中自动化创建图表的可视化方案

《C#高效实现在Word文档中自动化创建图表的可视化方案》本文将深入探讨如何利用C#,结合一款功能强大的第三方库,实现在Word文档中自动化创建图表,为你的数据呈现和报告生成提供一套实用且高效的解决方... 目录Word文档图表自动化:为什么选择C#?从零开始:C#实现Word文档图表的基本步骤深度优化:C

在C#中分离饼图的某个区域的操作指南

《在C#中分离饼图的某个区域的操作指南》在处理Excel饼图时,我们可能需要将饼图的各个部分分离出来,以使它们更加醒目,Spire.XLS提供了Series.DataFormat.Percent属性,... 目录引言如何设置饼图各分片之间分离宽度的代码示例:从整个饼图中分离单个分片的代码示例:引言在处理

C#借助Spire.XLS for .NET实现在Excel中添加文档属性

《C#借助Spire.XLSfor.NET实现在Excel中添加文档属性》在日常的数据处理和项目管理中,Excel文档扮演着举足轻重的角色,本文将深入探讨如何在C#中借助强大的第三方库Spire.... 目录为什么需要程序化添加Excel文档属性使用Spire.XLS for .NET库实现文档属性管理Sp

C++,C#,Rust,Go,Java,Python,JavaScript的性能对比全面讲解

《C++,C#,Rust,Go,Java,Python,JavaScript的性能对比全面讲解》:本文主要介绍C++,C#,Rust,Go,Java,Python,JavaScript性能对比全面... 目录编程语言性能对比、核心优势与最佳使用场景性能对比表格C++C#RustGoJavapythonjav

C# 预处理指令(# 指令)的具体使用

《C#预处理指令(#指令)的具体使用》本文主要介绍了C#预处理指令(#指令)的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录1、预处理指令的本质2、条件编译指令2.1 #define 和 #undef2.2 #if, #el

C#实现将Excel工作表拆分为多个窗格

《C#实现将Excel工作表拆分为多个窗格》在日常工作中,我们经常需要处理包含大量数据的Excel文件,本文将深入探讨如何在C#中利用强大的Spire.XLSfor.NET自动化实现Excel工作表的... 目录为什么需要拆分 Excel 窗格借助 Spire.XLS for .NET 实现冻结窗格(Fro