【问题标题】:Is parallel asynchronous execution where a thread sleeps using multiple threads?线程使用多个线程休眠的并行异步执行?
【发布时间】:2020-12-06 18:00:51
【问题描述】:

这是我为更好地理解异步方法而编写的代码。我知道异步方法与多线程不同,但在这种特定情况下似乎并非如此:

class Program
{
    static void Main(string[] args)
    {
        Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
        //the line above just makes sure that the console output uses . to represent doubles instead of ,
        ExecuteAsync();
        Console.ReadLine();
    }

    private static async Task ParallelAsyncMethod() //this is the method where async parallel execution is taking place
    {
        List<Task<string>> tasks = new List<Task<string>>();
        for (int i = 0; i < 5; i++)
        {
            tasks.Add(Task.Run(() => DownloadWebsite()));
        }

        var strings = await Task.WhenAll(tasks);
        foreach (var str in strings)
        {
            Console.WriteLine(str);
        }
    }

    private static string DownloadWebsite() //Imitating a website download
    {
        Thread.Sleep(1500); //making the thread sleep for 1500 miliseconds before returning
        return "Download finished";
    }

    private static async void ExecuteAsync()
    {
        var watch = Stopwatch.StartNew();
        await ParallelAsyncMethod();
        watch.Stop();
        
        Console.WriteLine($"It took the machine {watch.ElapsedMilliseconds} milliseconds" +
            $" or {Convert.ToDouble(watch.ElapsedMilliseconds) / 1000} seconds to complete this task");
        Console.ReadLine();
    }
}

//OUTPUT:
    /*
    Download finished
    Download finished
    Download finished
    Download finished
    Download finished
    It took the machine 1537 milliseconds or 1.537 seconds to complete this task
    */

如您所见,DownloadWebsite 方法等待 1.5 秒,然后返回“a”。名为ParallelAsyncMethod 的方法将其中五个方法添加到“任务”列表中,然后开始并行异步执行。如您所见,我还跟踪了执行ExecuteAsync 方法所需的时间。结果总是在 1540 毫秒左右。这是我的问题:如果DownloadWebsite 方法需要一个线程在1500 毫秒内休眠5 次,这是否意味着这些方法的并行执行需要5 个不同的线程?如果不是,那为什么程序只用了 1540 毫秒而不是 ~7500 毫秒?

【问题讨论】:

标签: c# multithreading asynchronous parallel-processing async-await


【解决方案1】:

我知道异步方法和多线程不一样

没错,异步方法在 I/O 发生时释放当前线程,并在其完成后安排继续。

异步和线程是完全不相关的概念。

但在这种特殊情况下似乎并非如此

这是因为您使用Task.Run 在线程池上显式运行DownloadWebsite,它通过在指示提供的委托运行后返回Task 来模拟异步代码。

因为您没有等待每个Task 完成后才开始下一个,所以可以同时使用多个线程。

当前每个线程都被阻塞,因为您在 DownloadWebsite 的实现中使用了 Thread.Sleep,这意味着您实际上在 ThreadPool 上运行了 5 个同步方法。


在生产代码中,您的DownloadWebsite 方法应该异步编写,可能使用HttpClient.GetAsync

private static async Task<string> DownloadWebsiteAsync()
{
    //...
    await httpClinet.GetAsync(//...
    //...
}

在这种情况下,GetAsync 返回一个Task,并在等待 HTTP 响应的同时释放当前线程

您仍然可以同时运行多个异步方法,但是由于每次都会释放线程,这可能会使用少于 5 个单独的线程,甚至可能使用单个线程。

确保不要将Task.Run 与异步方法一起使用;这只会增加不必要的开销:

var tasks = new List<Task<string>>();
for (int i = 0; i < 5; i++)
{
    tasks.Add(DownloadWebsiteAsync()); // No need for Task.Run
}

var strings = await Task.WhenAll(tasks);

顺便说一句,如果您想模拟异步操作,请使用 Task.Delay 而不是 Thread.Sleep,因为前者是非阻塞的:

private static async Task<string> DownloadWebsite() //Imitating a website download
{
    await Task.Delay(1500); // Release the thread for ~1500ms before continuing
    return "Download finished";
}

【讨论】:

  • 感谢您的回答!不过,我想澄清一件事。 “释放线程”是什么意思?
  • @Itsme1 与其在等待 I/O 响应时阻塞线程,不如将其释放到 ThreadPool 以服务其他请求。如果您的目标是桌面应用程序,这也可能是 UI 线程,并且释放线程保持 UI 响应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-08
相关资源
最近更新 更多