简体   繁体   English

异步任务与异步无效

[英]async Task vs async void

This might be a very stupid question, but I have the following lines of coding that convert RAW images to BitmapImages:这可能是一个非常愚蠢的问题,但我有以下几行代码可以将 RAW 图像转换为 BitmapImages:

public async void CreateImageThumbnails(string imagePath, int imgId)
{
    await Task.Run(() => controlCollection.Where(x => x.ImageId == imgId).FirstOrDefault().ImageSource = ThumbnailCreator.CreateThumbnail(imagePath));
}

which calls this method CreateThumbnail()调用此方法CreateThumbnail()

public static BitmapImage CreateThumbnail(string imagePath)
{
    var bitmap = new BitmapImage();

    using (var stream = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
    {
        bitmap.BeginInit();
        bitmap.DecodePixelWidth = 283;
        bitmap.CacheOption = BitmapCacheOption.OnLoad;
        bitmap.StreamSource = stream;
        bitmap.EndInit();
    }

    bitmap.Freeze();

    GC.WaitForPendingFinalizers();
    GC.Collect();

    return bitmap;
}

When using async Void instead of async Task in my CreateImageThumbnails method, my application processes the images(29 of them) about 11 seconds faster than async Task .在我的CreateImageThumbnails方法中使用async Void而不是async Task时,我的应用程序处理图像(其中 29 个)比async Task快约 11 秒。 Why would this be?为什么会这样?

async void异步无效异步无效

async task异步任务异步任务

The memory usage is much more using void , but the operation is completed much quicker.使用void占用的内存更多,但操作完成更快。 I have little knowledge of threading, this is why I am asking this question.我对线程知之甚少,这就是我问这个问题的原因。 Can someone please explain why this is happening?有人可以解释为什么会这样吗?

Also I have done some research on on when and when not to use async void , but I could not find an answer to my question.此外,我对何时以及何时不使用async void进行了一些研究,但我找不到我的问题的答案。 (I might just not have searched very well). (我可能只是没有很好地搜索)。

Thank you.谢谢。

When you call an async void method, or call an async Task method without awaiting it (if the called method contains an await , so it doesn't block), your code will continue right away, without waiting for the method to actually complete.当您调用async void方法,或在不等待的情况下调用async Task方法(如果被调用的方法包含await ,则它不会阻塞),您的代码将立即继续,无需等待该方法实际完成。 This means that several invocations of the method can be executing in parallel , but you won't know when they actually complete, which you usually need to know.这意味着该方法的多个调用可以并行执行,但您不知道它们何时真正完成,而您通常需要知道这一点。

You can take advantage of executing in parallel like this, while also being able to wait for all the invocations to complete by storing the Task s in a collection and then using await Task.WhenAll(tasks);您可以像这样利用并行执行,同时还可以通过Task存储在集合中然后使用await Task.WhenAll(tasks);来等待所有调用完成await Task.WhenAll(tasks); . .

Also keep in mind that if you want to execute code in parallel, you have to make sure it's safe to do it.还要记住,如果你想并行执行代码,你必须确保这样做是安全的。 This is commonly called "thread-safety".这通常称为“线程安全”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM