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

相关文章

高效+灵活,万博智云全球发布AWS无代理跨云容灾方案!

摘要 近日,万博智云推出了基于AWS的无代理跨云容灾解决方案,并与拉丁美洲,中东,亚洲的合作伙伴面向全球开展了联合发布。这一方案以AWS应用环境为基础,将HyperBDR平台的高效、灵活和成本效益优势与无代理功能相结合,为全球企业带来实现了更便捷、经济的数据保护。 一、全球联合发布 9月2日,万博智云CEO Michael Wong在线上平台发布AWS无代理跨云容灾解决方案的阐述视频,介绍了

2. c#从不同cs的文件调用函数

1.文件目录如下: 2. Program.cs文件的主函数如下 using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using System.Windows.Forms;namespace datasAnalysis{internal static

在JS中的设计模式的单例模式、策略模式、代理模式、原型模式浅讲

1. 单例模式(Singleton Pattern) 确保一个类只有一个实例,并提供一个全局访问点。 示例代码: class Singleton {constructor() {if (Singleton.instance) {return Singleton.instance;}Singleton.instance = this;this.data = [];}addData(value)

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

用命令行的方式启动.netcore webapi

用命令行的方式启动.netcore web项目 进入指定的项目文件夹,比如我发布后的代码放在下面文件夹中 在此地址栏中输入“cmd”,打开命令提示符,进入到发布代码目录 命令行启动.netcore项目的命令为:  dotnet 项目启动文件.dll --urls="http://*:对外端口" --ip="本机ip" --port=项目内部端口 例: dotnet Imagine.M

js异步提交form表单的解决方案

1.定义异步提交表单的方法 (通用方法) /*** 异步提交form表单* @param options {form:form表单元素,success:执行成功后处理函数}* <span style="color:#ff0000;"><strong>@注意 后台接收参数要解码否则中文会导致乱码 如:URLDecoder.decode(param,"UTF-8")</strong></span>

ActiveMQ—消息特性(延迟和定时消息投递)

ActiveMQ消息特性:延迟和定时消息投递(Delay and Schedule Message Delivery) 转自:http://blog.csdn.net/kimmking/article/details/8443872 有时候我们不希望消息马上被broker投递出去,而是想要消息60秒以后发给消费者,或者我们想让消息没隔一定时间投递一次,一共投递指定的次数。。。 类似

PostgreSQL核心功能特性与使用领域及场景分析

PostgreSQL有什么优点? 开源和免费 PostgreSQL是一个开源的数据库管理系统,可以免费使用和修改。这降低了企业的成本,并为开发者提供了一个活跃的社区和丰富的资源。 高度兼容 PostgreSQL支持多种操作系统(如Linux、Windows、macOS等)和编程语言(如C、C++、Java、Python、Ruby等),并提供了多种接口(如JDBC、ODBC、ADO.NET等

详解Tomcat 7的七大新特性和新增功能(1)

http://developer.51cto.com/art/201009/228537.htm http://tomcat.apache.org/tomcat-7.0-doc/index.html  Apache发布首个Tomcat 7版本已经发布了有一段时间了,Tomcat 7引入了许多新功能,并对现有功能进行了增强。很多文章列出了Tomcat 7的新功能,但大多数并没有详细解释它们

C# dateTimePicker 显示年月日,时分秒

dateTimePicker默认只显示日期,如果需要显示年月日,时分秒,只需要以下两步: 1.dateTimePicker1.Format = DateTimePickerFormat.Time 2.dateTimePicker1.CustomFormat = yyyy-MM-dd HH:mm:ss Tips:  a. dateTimePicker1.ShowUpDown = t