2021年12月4日 星期六

TaskCompletionSource包同步變成非同步

最近有效能問題,就是要去呼叫某個類別庫的Method

而且這些Method都沒有寫非同步,所以在要讓N個Method同時跑增快速度好像不太行

某些歷史因素要加多弄個非同步Method比較麻煩也耗時

所以一開始有想到直接用Task.Run直接包N個Method直接跑

但這樣會吃到站台的執行緒,於是去查了一下

居然有TaskCompletionSource來把同步Method變成非同步Method

 
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var task1 = GetData1Async();
            var task2 = GetData2Async();

            Console.WriteLine(await task1);
            Console.WriteLine(await task2);
            Console.ReadLine();
        }


        public static Task<string> GetData1Async()
        {
            var taskSource = new TaskCompletionSource<string>();
            var result = string.Empty;
            try
            {
                taskSource.SetResult(GetData1());
            }
            catch(Exception ex)
            {
                taskSource.SetException(ex);
            }
            return taskSource.Task;
        }

        public static Task<string> GetData2Async()
        {
            var taskSource = new TaskCompletionSource<string>();
            var result = string.Empty;
            try
            {
                taskSource.SetResult(GetData2());
            }
            catch (Exception ex)
            {
                taskSource.SetException(ex);
            }
            return taskSource.Task;
        }

        public static string GetData1()
        {
            return "GetData1...";
        }

        public static string GetData2()
        {
            return "GetData2...";
        }
    }
}

沒有留言:

張貼留言