在ASP.NET应用程序执行多个线程的方法 [英] In an ASP.NET app execute methods on multiple threads

查看:90
本文介绍了在ASP.NET应用程序执行多个线程的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET应用程序,其中一个请求调用6很慢的方法。该方法不是异步和我没有重新编写和测试他们的时间。我怎样才能运行6个线程的6方法,然后agregate的结果?我在.NET 4.5。

I have an ASP.NET app, where a single request invokes 6 very slow methods. The methods are not async and I don't have the time to rewrite and test them. How can I run those 6 methods on 6 threads and then agregate the results? I'm on .NET 4.5.

推荐答案

您可以简单地使用 Task.Run 来创建一个运行每种方法在另一个线程任务,然后等待他们全部完成,这样就可以使用的结果。

You can simply use Task.Run to create a task that runs each of the methods in another thread, and then wait for them all to finish so that you can use the results.

var tasks = new Task<YourResultType>[]
{
    Task.Run(() => Method1()),
    Task.Run(() => Method2()),
    Task.Run(() => Method3()),
    Task.Run(() => Method4()),
    Task.Run(() => Method5()),
    Task.Run(() => Method6()),
};

var results = Task.WhenAll(tasks).Result;

如果该方法并不都具有相同类型的结果,让您把所有的任务到一个数组,那么你就需要有独立的局部变量为每个任务,并使用结果对每个人开始他们毕竟。

If the methods don't all have results of the same type, allowing you to put all of the tasks into an array, then you'll need to have separate local variables for each task and use Result on each one after starting them all.

这篇关于在ASP.NET应用程序执行多个线程的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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