异步任务与异步无效 [英] async Task vs async void

查看:118
本文介绍了异步任务与异步无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常愚蠢的问题,但是我有以下几行代码将RAW图像转换为BitmapImages:

This might be a very stupid question, but I have the following lines of coding that convert RAW images to BitmapImages:

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

调用此方法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;
}

在我的CreateImageThumbnails方法中使用async Void而不是async Task时,我的应用程序处理图像(其中的29个)的速度比async Task快11秒.为什么会这样呢?

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. Why would this be?

异步无效

async void

异步任务

async task

使用void可以更多地使用内存,但是很多可以更快地完成操作.我对线程几乎一无所知,这就是为什么我要问这个问题.有人可以解释为什么会这样吗?

The memory usage is much more using void, but the operation is completed much quicker. I have little knowledge of threading, this is why I am asking this question. Can someone please explain why this is happening?

我还对何时以及何时不使用async void做过一些研究,但是我找不到我的问题的答案. (我可能搜索的不是很好).

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. (I might just not have searched very well).

谢谢.

推荐答案

当您调用async void方法或在不等待它的情况下调用async Task方法时(如果被调用的方法包含await,则它不会't block),您的代码将立即继续运行,而无需等待方法真正完成.这意味着该方法的多个调用可以并行执行 ,但是您通常不知道它们何时真正完成.

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. 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.

您可以利用像这样并行执行的优势,同时还可以通过Task s存储在集合中然后使用await Task.WhenAll(tasks);来等待所有调用完成.

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 Tasks in a collection and then using 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".

这篇关于异步任务与异步无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆