相关疑难解决方法(0)

Async和Await的工作原理

我试图了解Async和Await是如何工作的.如何控制程序中的旅行.这是我试图理解的代码.

public async Task MyMethod()
{
    Task<int> longRunningTask = LongRunningOperation();
    //indeed you can do independent to the int result work here 
    MySynchronousMethod();
    //and now we call await on the task 
    int result = await longRunningTask;
    //use the result 
    Console.WriteLine(result);
}

public async Task<int> LongRunningOperation() // assume we return an int from this long running operation 
{
    await Task.Delay(5000); //5 seconds delay
    return 1;
}

private void Button_Click_3(object sender, RoutedEventArgs e)
{
     MyMethod();
}
Run Code Online (Sandbox Code Playgroud)

当按钮点击发生时,MyMethod()将被调用,并且将调用MyMethod LongRunningOperation(),并且需要5秒才能完成.所以我的问题是

  • 这条线的意义是什么?

    任务longRunningTask …

c# async-await

10
推荐指数
3
解决办法
2万
查看次数

.NET 是否在新的不同线程池线程上恢复等待继续,还是重用先前恢复的线程?

.NET 是否在新的不同线程池线程上恢复等待继续,还是重用先前恢复的线程?

让我们在下面的 .NET Core 控制台应用程序中的 C# 代码中想象一下:

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

namespace NetCoreResume
{
    class Program
    {
        static async Task AsyncThree()
        {
            await Task.Run(() =>
            {
                Console.WriteLine($"AsyncThree Task.Run thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
            });

            Console.WriteLine($"AsyncThree continuation thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
        }

        static async Task AsyncTwo()
        {
            await AsyncThree();

            Console.WriteLine($"AsyncTwo continuation thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
        }

        static async Task AsyncOne()
        {
            await AsyncTwo();

            Console.WriteLine($"AsyncOne continuation thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
        }

        static void Main(string[] args)
        {
            AsyncOne().Wait();

            Console.WriteLine("Press any key to end...");
            Console.ReadKey();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它会输出:

AsyncThree …
Run Code Online (Sandbox Code Playgroud)

c# multithreading asynchronous async-await

4
推荐指数
1
解决办法
823
查看次数

标签 统计

async-await ×2

c# ×2

asynchronous ×1

multithreading ×1