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#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

C#实现一键批量合并PDF文档

《C#实现一键批量合并PDF文档》这篇文章主要为大家详细介绍了如何使用C#实现一键批量合并PDF文档功能,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言效果展示功能实现1、添加文件2、文件分组(书签)3、定义页码范围4、自定义显示5、定义页面尺寸6、PDF批量合并7、其他方法

C#下Newtonsoft.Json的具体使用

《C#下Newtonsoft.Json的具体使用》Newtonsoft.Json是一个非常流行的C#JSON序列化和反序列化库,它可以方便地将C#对象转换为JSON格式,或者将JSON数据解析为C#对... 目录安装 Newtonsoft.json基本用法1. 序列化 C# 对象为 JSON2. 反序列化

C#文件复制异常:"未能找到文件"的解决方案与预防措施

《C#文件复制异常:未能找到文件的解决方案与预防措施》在C#开发中,文件操作是基础中的基础,但有时最基础的File.Copy()方法也会抛出令人困惑的异常,当targetFilePath设置为D:2... 目录一个看似简单的文件操作问题问题重现与错误分析错误代码示例错误信息根本原因分析全面解决方案1. 确保

基于C#实现PDF转图片的详细教程

《基于C#实现PDF转图片的详细教程》在数字化办公场景中,PDF文件的可视化处理需求日益增长,本文将围绕Spire.PDFfor.NET这一工具,详解如何通过C#将PDF转换为JPG、PNG等主流图片... 目录引言一、组件部署二、快速入门:PDF 转图片的核心 C# 代码三、分辨率设置 - 清晰度的决定因

C# LiteDB处理时间序列数据的高性能解决方案

《C#LiteDB处理时间序列数据的高性能解决方案》LiteDB作为.NET生态下的轻量级嵌入式NoSQL数据库,一直是时间序列处理的优选方案,本文将为大家大家简单介绍一下LiteDB处理时间序列数... 目录为什么选择LiteDB处理时间序列数据第一章:LiteDB时间序列数据模型设计1.1 核心设计原则

Python异步编程之await与asyncio基本用法详解

《Python异步编程之await与asyncio基本用法详解》在Python中,await和asyncio是异步编程的核心工具,用于高效处理I/O密集型任务(如网络请求、文件读写、数据库操作等),接... 目录一、核心概念二、使用场景三、基本用法1. 定义协程2. 运行协程3. 并发执行多个任务四、关键

C#高效实现Word文档内容查找与替换的6种方法

《C#高效实现Word文档内容查找与替换的6种方法》在日常文档处理工作中,尤其是面对大型Word文档时,手动查找、替换文本往往既耗时又容易出错,本文整理了C#查找与替换Word内容的6种方法,大家可以... 目录环境准备方法一:查找文本并替换为新文本方法二:使用正则表达式查找并替换文本方法三:将文本替换为图

C#使用Spire.XLS快速生成多表格Excel文件

《C#使用Spire.XLS快速生成多表格Excel文件》在日常开发中,我们经常需要将业务数据导出为结构清晰的Excel文件,本文将手把手教你使用Spire.XLS这个强大的.NET组件,只需几行C#... 目录一、Spire.XLS核心优势清单1.1 性能碾压:从3秒到0.5秒的质变1.2 批量操作的优雅