天天看點

C#中await Task.Run 傳回值

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

namespace ConsoleApp3
{
    class Program
    {
        public static void Main()
        {
            Console.WriteLine($"主線程:\t\t\t線程Id:【{Environment.CurrentManagedThreadId}】\t背景線程:【{Thread.CurrentThread.IsBackground}】\t使用線程池:【{Thread.CurrentThread.IsThreadPoolThread}】\t目前時間:【{DateTime_Now_ToString()}】");
            string result = GetAwaitString("abc123").Result;
            Console.WriteLine("結果:" + result);
            Console.WriteLine("執行完畢:" + DateTime_Now_ToString());
            Console.ReadLine();
        }

        public static string DateTime_Now_ToString()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff");
        }

        private static async Task<string> GetAwaitString(string str)
        {
            /*
                async Task<string> GetAwaitRunString(string str) 方法内部是同步執行的。
                直到運作到 await 關鍵字(内部)是異步執行的(使用背景線程池)。
             */
            Console.WriteLine("GetAwaitString await前:\t線程Id:【{0}】\t背景線程:【{1}】\t使用線程池:【{2}】\t目前時間:【{3}】",
                Environment.CurrentManagedThreadId.ToString(),
                Thread.CurrentThread.IsBackground,
                Thread.CurrentThread.IsThreadPoolThread,
                DateTime_Now_ToString());

            var task = await Task.Run<string>(() =>
            {
                Console.WriteLine("GetAwaitString await後:\t線程Id:【{0}】\t背景線程:【{1}】\t使用線程池:【{2}】\t目前時間:【{3}】",
                Environment.CurrentManagedThreadId.ToString(),
                Thread.CurrentThread.IsBackground,
                Thread.CurrentThread.IsThreadPoolThread,
                DateTime_Now_ToString());
                return str + "," + DateTime_Now_ToString();
            });

            return task;
        }
    }
}
           
C#中await Task.Run 傳回值

繼續閱讀