zoukankan      html  css  js  c++  java
  • C#多线程---委托实现异步

    一、概述

    通过调用ThreadPool的QueueUserWorkItem方法来来启动工作者线程非常方便,但委托WaitCallback指向的是带有一个参数的无返回值的方法。

    如果我们实际操作中需要有返回值,或者需要带有多个参数, 这时通过这样的方式就难以实现, 为了解决这样的问题,我们可以通过委托来建立工作者线程。

    异步委托所执行的函数运行在线程池中,属于后台线程。

    二、例子

     1 using System;
     2 using System.Threading;
     3 
     4 namespace DelegateBeginInvoke
     5 {
     6     class Program
     7     {
     8         delegate string MyDelegate(string str1, string str2);
     9         static void Main(string[] args)
    10         {
    11             MyDelegate del = new MyDelegate(AsyncMethod);
    12             string str1 = "123";
    13             string str2 = "456";
    14            IAsyncResult result =  del.BeginInvoke(str1, str2,null, null);
    15             Console.WriteLine("Delegate begininvoke called");
    16             string myResult = del.EndInvoke(result);
    17             Console.WriteLine($"Result is {myResult}");
    18 
    19         }
    20         private static string AsyncMethod(string str1, string str2)
    21         {
    22             PrintThreadInfo("Print info in AsyncMethod");
    23             string myString = str1 + str2;
    24             Thread.Sleep(6000);
    25             return myString;
    26         }
    27         private static void PrintThreadInfo(string info)
    28         {
    29             Console.WriteLine(info);
    30             Console.WriteLine($"ThreadId:{Thread.CurrentThread.ManagedThreadId}
    IsBackgroundThread:{Thread.CurrentThread.IsBackground}
    IsThreadPoolThread:{Thread.CurrentThread.IsThreadPoolThread}");
    31             int workerThread = 0;
    32             int ioThread = 0;
    33             ThreadPool.GetMaxThreads(out workerThread, out ioThread);
    34             Console.WriteLine($"MaxWorkerThread:{workerThread}
    MaxIoThread:{ioThread}");
    35             int workerThreadAvailable = 0;
    36             int ioThreadAvailable = 0;
    37             ThreadPool.GetAvailableThreads(out workerThreadAvailable, out ioThreadAvailable);
    38             Console.WriteLine($"AvailableWorkerThread:{workerThreadAvailable}
    AvailableIoThread:{ioThreadAvailable}");
    39         }
    40     }
    41 }
    View Code

    运行结果如下:

    注:EndInvoke会阻塞当前调用线程,直到工作者线程执行完毕,获得结果。

  • 相关阅读:
    双11专刊|云原生数据仓库AnalyticDB支撑双11,大幅提升分析实时性和用户体验
    LeetCode_Binary Tree Inorder Traversal
    LeetCode_4Sum
    LeetCode_Add Binary
    LeetCode_Add Two Numbers
    LeetCode_3Sum Closest
    Building CEGUI with Ogre 1.8.1
    LeetCode_3Sum
    LeetCode_Climbing Stairs
    LeetCode_Binary Tree Level Order Traversal
  • 原文地址:https://www.cnblogs.com/3xiaolonglong/p/9629761.html
Copyright © 2011-2022 走看看