简体   繁体   English

在新线程上启动方法时使用async关键字是否有效率?

[英]Is it more or less efficient to use the async keyword along with starting the method on a new thread?

I have a program that downloads alot of data from the internet and saves it to my local db using the Entity Framework. 我有一个程序可以从网上下载大量数据,然后使用实体框架将其保存到本地数据库中。 I have this sample code below. 我在下面有此示例代码。 Is it more efficient for me to start the method on a new thread and also use the async keyword when it is saving the model data or is this less efficient. 对我来说,在新线程上启动方法并在保存模型数据时也使用async关键字是否效率更高?

static void Main(string[] args)
    {
        using (DBModel model = new DBModel())
        {
            model.Database.Connection.Open();

            Task task = Task.Factory.StartNew(() => downloadData(model));
            task.Wait();
        }

    }

public static async Task<string> downloadData(DBModel model)
    {
        // do something first
        await model.SaveChangesAsync();
    }

Is it more efficient... 效率更高吗?

That's the wrong question. 那是个错误的问题。 It's better to first consider which is more correct , and then search for more efficient methods once you have a proven performance problem in production code. 最好先考虑哪种方法更正确 ,然后在生产代码中证明性能问题后再搜索更有效的方法。

async methods should be used when doing operations that are naturally asynchronous. 在执行自然异步的操作时,应使用async方法。 This includes any kind of I/O, such as downloading data from the Internet and EF. 这包括任何类型的I / O,例如从Internet和EF下载数据。

Multithreading should be used if you want to free up the current thread when doing operations that are CPU-bound. 如果要在执行CPU绑定的操作时释放当前线程,则应使用多线程。 You can use Task.Run (not StartNew , please ) to push work off to a background thread. 您可以使用Task.Run不要使用StartNew )将工作推送到后台线程。

In your situation, just using async / await is more correct. 在您的情况下,仅使用async / await更为正确。

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

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