编写使用异步多线程的方法/等待在.NET 4.5 [英] Writing multithreaded methods using async/await in .Net 4.5

查看:147
本文介绍了编写使用异步多线程的方法/等待在.NET 4.5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的查询。

我承认,我没有使用.NET 4.5之前的多线程多,但随着新的异步/的await 的功能,我决定试一试。我开始用它进行试验和一切似乎不错,但我没能找到我的问题的解决方案在网络上的任何地方。

I admit that I haven't use multithreading much before .Net 4.5, but with the new async/await functionality I decided to give it a try. I started experimenting with it and all seems fine, but I wasn't able to find a solution for my "problem" anywhere on the web.

这样大家讲解如何等待可与.NET平台的新转换的方法来使用(如 WriteAsync() ReadAsync()等),但如果我想用我自己的方法是什么?例如,可以说,我执行一个非常昂贵的计算和希望所有我的4个内核上工作。我会与此类似:

So everyone explain how await can be used with the newly transformed methods of the .Net platform (e.g. WriteAsync(), ReadAsync() etc...), but what if I wanted to use it for my own methods? For example, lets say that I am performing an extremely expensive calculation and want all of my 4 cores working on it. I would have something similar to this:

async Task DoLotsOfWork<T>(T[] data, int start, int end)
{
    //Do very expensive work
}

但因为我没有一个的await 关键词在那里,法只是当作一个同步。我想叫它从外面4倍,这样它可以在我所有的内核上运行,而我显示给用户的东西明智的(例如,请稍候...)。我能够想出的唯一解决办法是添加一个等待Task.Yield(); 在方法的开始。事情是这样的:

But since I don't have an await keyword there, the method is just treated as a synchronous one. I would like to call it 4 times from outside so that it can run on all of my cores, while I display something sensible to the user(e.g. "Please wait..."). The only solution that I was able to figure out was to add a await Task.Yield(); in the start of the method. Something like this:

async Task DoLotsOfWork<T>(T[] data, int start, int end)
{
    await Task.Yield();
    //Do very expensive work
}

在这种情况下,该方法将表现为我希望它。但有这更好的解决办法?我觉得这应该比究竟写这行code更容易/更明智。我知道我可以创建一个任务/线程对象,并调用开始()方法,但需要更工作。我只是想,在新的异步/等待功能,这样的事情会更容易些。

In that case, the method would behave as I would expect it to. But is there a better solution for this? I feel that it should be easier/more sensible than writing exactly that line of code. I understand that I can create a Task/Thread object and call the Start() method, but that requires even more work. I just thought that with the new async/await functionality this sort of thing would be easier.

推荐答案

于是开始与你需要,做了非常昂贵的同步工作的方法:

So to start with you'll need a method that does the very expensive work synchronously:

public void DoLotsOfWork<T>(T[] data, int start, int end) 
{
    Thread.Sleep(5000);//placeholder for real work
}

然后我们可以使用 Task.Run 来开始这项工作的多个实例在一个线程池线程。

Then we can use Task.Run to start multiple instances of this work in a threadpool thread.

List<Task> tasks = new List<Task>();
for(int i = 0; i < 4; i++)
{
    tasks.Add(Task.Run(()=>DoLotsOfWork(data, start, end));
}

然后,我们可以做一个非阻塞等到所有的人都做了:

Then we can do a non-blocking wait until all of them are done:

await Task.WhenAll(tasks);

这篇关于编写使用异步多线程的方法/等待在.NET 4.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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