C#使用异步方式调用同步方法的实现方法

使用异步方式调用同步方法,在此我们使用异步编程模型(APM)实现
1、定义异步委托和测试方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ApmAsyncApp
{
    public delegate string TestMethodAsyncCaller(int callDuration, out int threadId);
    /// <summary>
    internal class AsyncDemo
    {
        
        /// 执行异步调用的方法
        /// </summary>
        /// <param name="callDuration"></param>
        /// <param name="threadId"></param>
        /// <returns></returns>
        public string TestMethod(int callDuration,out int threadId)
        {
            Console.WriteLine("Test method begins:");
            Thread.Sleep(callDuration);
            threadId=Thread.CurrentThread.ManagedThreadId;
            return String.Format("Call time was {0}",callDuration);
        }
    }
}

2、使用 EndInvoke 等待异步调用

static void Main(string[] args)
        {
            int threadId;
            //创建测试类
            AsyncDemo asyncDemo = new AsyncDemo();
            //创建委托
            TestMethodAsyncCaller caller = new TestMethodAsyncCaller(asyncDemo.TestMethod);
            //初始化异步调用
            IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null);
            Thread.Sleep(0);
            Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId);
            //调用EndInvoke检索结果
            string returnValue = caller.EndInvoke(out threadId, result);
            Console.WriteLine("The call executed on thread {0},with return value \"{1}\".", threadId, returnValue);
            Console.ReadLine();
        }

在这里插入图片描述
3、使用 WaitHandle 等待异步调用

static void Main(string[] args)
        {
            int threadId;
            //创建测试类
            AsyncDemo asyncDemo = new AsyncDemo();
            //创建委托
            TestMethodAsyncCaller caller = new TestMethodAsyncCaller(asyncDemo.TestMethod);
            //初始化异步调用
            IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null);
            Thread.Sleep(0);
            Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId);
            //sone to do
            //等待信号
            result.AsyncWaitHandle.WaitOne();
            //调用EndInvoke检索结果
            string returnValue = caller.EndInvoke(out threadId, result);
            result.AsyncWaitHandle.Close();
            Console.WriteLine("The call executed on thread {0},with return value \"{1}\".", threadId, returnValue);
            Console.ReadLine();
        }

在这里插入图片描述
4、对异步调用的完成情况进行轮询

static void Main(string[] args)
        {
            int threadId;
            //创建测试类
            AsyncDemo asyncDemo = new AsyncDemo();
            //创建委托
            TestMethodAsyncCaller caller = new TestMethodAsyncCaller(asyncDemo.TestMethod);
            //初始化异步调用
            IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null);
            Thread.Sleep(0);
            Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId);
            // 等待完成.
            while (result.IsCompleted == false)
            {
                Thread.Sleep(250);
                Console.Write(".");
            }
            //调用EndInvoke检索结果
            string returnValue = caller.EndInvoke(out threadId, result);
            Console.WriteLine("The call executed on thread {0},with return value \"{1}\".", threadId, returnValue);
            Console.ReadLine();
        }

在这里插入图片描述
5、异步调用完成时执行回调方法

static void Main(string[] args)
        {
            int threadId = 0;
            //创建测试类
            AsyncDemo asyncDemo = new AsyncDemo();
            //创建委托
            TestMethodAsyncCaller caller = new TestMethodAsyncCaller(asyncDemo.TestMethod);
            //初始化异步调用
            IAsyncResult result = caller.BeginInvoke(3000, out threadId, new AsyncCallback(callbackMethod), "The call executed on thread {0},with return value \"{1}\".");
            Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(5000);
            Console.WriteLine("The main thread ends.");
            Console.ReadLine();
        }

        private static void callbackMethod(IAsyncResult ar)
        {
            //检索委托.
            AsyncResult result = (AsyncResult)ar;
            TestMethodAsyncCaller caller = (TestMethodAsyncCaller)result.AsyncDelegate;
            //格式字符串作为状态信息被传递
            string formatString = (string)ar.AsyncState;
            int threadId = 0;
            //调用EndInvoke检查结果.
            string returnValue = caller.EndInvoke(out threadId, ar);
            //用格式字符串格式化输出信息
            Console.WriteLine(formatString, threadId, returnValue);
        }

在这里插入图片描述

相关推荐

  1. C# 异步方法使用场景

    2024-07-12 14:12:01       45 阅读
  2. C# 方法递归调用

    2024-07-12 14:12:01       61 阅读
  3. 使用.net core 调用C#WebService三种方式

    2024-07-12 14:12:01       32 阅读
  4. 实现节流防止连点方法以及调用方式

    2024-07-12 14:12:01       37 阅读
  5. C#写入和调用方法

    2024-07-12 14:12:01       40 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 14:12:01       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 14:12:01       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 14:12:01       58 阅读
  4. Python语言-面向对象

    2024-07-12 14:12:01       69 阅读

热门阅读

  1. Django 表单

    2024-07-12 14:12:01       21 阅读
  2. 推荐系统名词解释

    2024-07-12 14:12:01       25 阅读
  3. 顺序表的应用之通讯录专题

    2024-07-12 14:12:01       21 阅读
  4. 自动驾驶决策和控制系统的研究

    2024-07-12 14:12:01       23 阅读
  5. 【史上最全面ESP32教程】http通信

    2024-07-12 14:12:01       21 阅读
  6. C++ STL常用容器之vector(顺序容器)

    2024-07-12 14:12:01       21 阅读
  7. SQL注入:时间盲注

    2024-07-12 14:12:01       24 阅读