Task.RunSynchronously()

作者:追风剑情 发布于:2024-1-22 15:19 分类:C#

[官方文档] Task.RunSynchronously 方法

任务同步运行,会阻塞调用线程。

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

namespace ConsoleApp11
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Application executing on thread {0}",
                        Thread.CurrentThread.ManagedThreadId);
            var asyncTask = Task.Run(() => {
                Console.WriteLine("Task {0} (asyncTask) executing on Thread {1}",
                                                                 Task.CurrentId,
                                                                 Thread.CurrentThread.ManagedThreadId);
                long sum = 0;
                for (int ctr = 1; ctr <= 1000000; ctr++)
                    sum += ctr;
                return sum;
            });
            var syncTask = new Task<long>(() => {
                Console.WriteLine("Task {0} (syncTask) executing on Thread {1}",
                                                                       Task.CurrentId,
                                                                       Thread.CurrentThread.ManagedThreadId);
                long sum = 0;
                for (int ctr = 1; ctr <= 1000000; ctr++)
                    sum += ctr;
                return sum;
            });
            syncTask.RunSynchronously();
            Console.WriteLine();
            Console.WriteLine("Task {0} returned {1:N0}", syncTask.Id, syncTask.Result);
            Console.WriteLine("Task {0} returned {1:N0}", asyncTask.Id, asyncTask.Result);

            Console.ReadKey();
        }
    }
}

运行测试

1111111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号