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# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin

从入门到精通C++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

C#如何去掉文件夹或文件名非法字符

《C#如何去掉文件夹或文件名非法字符》:本文主要介绍C#如何去掉文件夹或文件名非法字符的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C#去掉文件夹或文件名非法字符net类库提供了非法字符的数组这里还有个小窍门总结C#去掉文件夹或文件名非法字符实现有输入字

C#之List集合去重复对象的实现方法

《C#之List集合去重复对象的实现方法》:本文主要介绍C#之List集合去重复对象的实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C# List集合去重复对象方法1、测试数据2、测试数据3、知识点补充总结C# List集合去重复对象方法1、测试数据

C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式

《C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式》Markdown凭借简洁的语法、优良的可读性,以及对版本控制系统的高度兼容性,逐渐成为最受欢迎的文档格式... 目录为什么要将文档转换为 Markdown 格式使用工具将 Word 文档转换为 Markdown(.

Java调用C#动态库的三种方法详解

《Java调用C#动态库的三种方法详解》在这个多语言编程的时代,Java和C#就像两位才华横溢的舞者,各自在不同的舞台上展现着独特的魅力,然而,当它们携手合作时,又会碰撞出怎样绚丽的火花呢?今天,我们... 目录方法1:C++/CLI搭建桥梁——Java ↔ C# 的“翻译官”步骤1:创建C#类库(.NET

C#代码实现解析WTGPS和BD数据

《C#代码实现解析WTGPS和BD数据》在现代的导航与定位应用中,准确解析GPS和北斗(BD)等卫星定位数据至关重要,本文将使用C#语言实现解析WTGPS和BD数据,需要的可以了解下... 目录一、代码结构概览1. 核心解析方法2. 位置信息解析3. 经纬度转换方法4. 日期和时间戳解析5. 辅助方法二、L

使用C#删除Excel表格中的重复行数据的代码详解

《使用C#删除Excel表格中的重复行数据的代码详解》重复行是指在Excel表格中完全相同的多行数据,删除这些重复行至关重要,因为它们不仅会干扰数据分析,还可能导致错误的决策和结论,所以本文给大家介绍... 目录简介使用工具C# 删除Excel工作表中的重复行语法工作原理实现代码C# 删除指定Excel单元

JDK9到JDK21中值得掌握的29个实用特性分享

《JDK9到JDK21中值得掌握的29个实用特性分享》Java的演进节奏从JDK9开始显著加快,每半年一个新版本的发布节奏为Java带来了大量的新特性,本文整理了29个JDK9到JDK21中值得掌握的... 目录JDK 9 模块化与API增强1. 集合工厂方法:一行代码创建不可变集合2. 私有接口方法:接口

C#使用MQTTnet实现服务端与客户端的通讯的示例

《C#使用MQTTnet实现服务端与客户端的通讯的示例》本文主要介绍了C#使用MQTTnet实现服务端与客户端的通讯的示例,包括协议特性、连接管理、QoS机制和安全策略,具有一定的参考价值,感兴趣的可... 目录一、MQTT 协议简介二、MQTT 协议核心特性三、MQTTNET 库的核心功能四、服务端(BR