Task.Yield

        static void Main(string[] args)
        {
            Task.Run(() => RunAsync());
            Console.ReadLine();
        }

        static async Task RunAsync()
        {
            Console.WriteLine("RunAsync方法前" + System.Threading.Thread.CurrentThread.ManagedThreadId);
            Task<Task> task = null;
            task = getOwnTaskAsync();
            var foundTask = await task;
            Console.WriteLine("RunAsync方法后" +  System.Threading.Thread.CurrentThread.ManagedThreadId);

            async Task<Task> getOwnTaskAsync()
            {
                Console.WriteLine("前" + System.Threading.Thread.CurrentThread.ManagedThreadId);
                await Task.Yield();
                Console.WriteLine("后" + System.Threading.Thread.CurrentThread.ManagedThreadId);

                return task;
            }
        }

Task.Yield_第1张图片
此时getOwnTaskAsync方法中,Task.Yield()后面的代码将在一个新的异步线程中执行。如果注释掉Task.Yield(),则Task.Yield()后面的代码在相同中线程中执行。

        static void Main(string[] args)
        {
            Task.Run(() => RunAsync());
            Console.ReadLine();
        }

        static async Task RunAsync()
        {
            Console.WriteLine("RunAsync方法前" + System.Threading.Thread.CurrentThread.ManagedThreadId);
            Task<Task> task = null;
            task = getOwnTaskAsync();
            var foundTask = await task;
            Console.WriteLine("RunAsync方法后" +  System.Threading.Thread.CurrentThread.ManagedThreadId);

            async Task<Task> getOwnTaskAsync()
            {
                Console.WriteLine("前" + System.Threading.Thread.CurrentThread.ManagedThreadId);
                //await Task.Yield();
                Console.WriteLine("后" + System.Threading.Thread.CurrentThread.ManagedThreadId);

                return task;
            }
        }

Task.Yield_第2张图片

你可能感兴趣的:(c#)