ASP.NET多线程Web请求 [英] ASP.NET Multithreading Web Requests

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

问题描述

我正在ASP.NET解决方案中构建一个页面,该页面将从第三方API服务检索其大部分数据.

I'm building a page in my ASP.NET solution that retrieves most of its data from a 3rd Party API Service.

该页面本身将需要对API进行大约5个单独的不同调用,以填充其所有控件,因为对该API的每个Web请求都将带回不同的数据集.

The page itself will need to make approximately 5 individual different calls to the API to populate all of its controls, as each Web Request to the API brings back different sets of Data.

我想同时处理我在新线程上发出的每个单独的Web请求,从而减少了加载时间.

I would like to deal with each separate Web request i make on a new thread, simultaneously so that load time is reduced.

我提出的每个请求都是这样的:-

Each request I'm making looks like this :-

WebRequest request = WebRequest.Create(requestUrl);

string response = new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();

return new JsonSerializer().Deserialize<OccupationSearch>(new JsonTextReader(new StringReader(response)));

首先,我应该尝试这种方法吗?即安全吗?并通过将其多线程化来提高性能.

Firstly, should i be attempting this? i.e, is it safe? and will it enhance performance by multi-threading this out.

第二,执行此操作的最佳方法是什么?多线程系统有很多不同的方法,但是哪种方法最适合此任务?

Secondly, what is the best way to go about doing this? There's many different ways to multi-thread systems, but which will suit this task best?

推荐答案

多线程是正确的选择,但我将其称为异步处理.

Multi-threading is the right choice, but I would call it doing stuff asynchronously.

无论如何,您应该知道IIS中的多线程工作原理有所不同.

Anyway, you should know that multi-threading works different in IIS.

一旦所有子线程结束,IIS辅助进程将完成一个请求,这是一个大问题,因为您不想长时间保留一个辅助进程,而是将其重新用于其他请求.其实这是一个线程池.

IIS worker process will finish a request once all child threads end, and this is a big problem, because you don't want to hold a worker process for a long time but re-use it for other requests. Actually it's a thread pool.

这就是ASP.NET提供其自己的方法来实现异步的原因,如果使用正确的方法,则IIS将能够一次处理更多的请求,因为异步工作将在IIS流程模型之外执行.

This is why ASP.NET offers its own approach to implement asynchronity and if you use the right approach, IIS will be able to process more requests at once because asynchronous work will be executed outside IIS process model.

我建议您阅读有关ASP.NET异步的更多信息:

I would suggest you to read more about ASP.NET async:

  • http://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx

结论:使用异步工作,这将更有效地利用服务器资源,但首先请详细了解如何以正确的方式进行操作!

Conclusion: use asynchronous work and this will make a more efficient use of server resources, but first learn more about how to do it in the right way!

这篇关于ASP.NET多线程Web请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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