同时运行x个Web请求 [英] Run x number of web requests simultaneously

查看:62
本文介绍了同时运行x个Web请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们公司有一个Web服务,我想通过我自己的C#HTTPWebRequest客户端发送XML文件(存储在驱动器中).这已经有效. Web服务同时支持5个同步请求(服务器上的处理完成后,我会从Web服务获得响应).每个请求大约需要5分钟的处理时间.

Our company has a web service which I want to send XML files (stored on my drive) via my own HTTPWebRequest client in C#. This already works. The web service supports 5 synchronuous requests at the same time (I get a response from the web service once the processing on the server is completed). Processing takes about 5 minutes for each request.

抛出太多请求(> 5)导致我的客户端超时.同样,这可能导致服务器端错误和数据不一致.不能在服务器端进行更改(来自其他供应商).

Throwing too many requests (> 5) results in timeouts for my client. Also, this can lead to errors on the server side and incoherent data. Making changes on the server side is not an option (from different vendor).

现在,我的Webrequest客户端将发送XML并使用result.AsyncWaitHandle.WaitOne();

Right now, my Webrequest client will send the XML and wait for the response using result.AsyncWaitHandle.WaitOne();

但是,通过这种方式,尽管Web服务支持5,但一次只能处理一个请求.我尝试使用BackgroundworkerThreadpool,但是它们同时创建了太多请求,这对我来说毫无用处.有什么建议,如何解决这个问题?用5个线程创建我自己的Threadpool?有什么建议,如何实现?

However, this way, only one request can be processed at a time although the web service supports 5. I tried using a Backgroundworker and Threadpool but they create too many requests at same, which make them useless to me. Any suggestion, how one could solve this problem? Create my own Threadpool with exactly 5 threads? Any suggestions, how to implement this?

推荐答案

最简单的方法是创建5个线程(除了:这是一个奇数!),这些线程使用BlockingCollection中的xml文件.

The easy way is to create 5 threads ( aside: that's an odd number! ) that consume the xml files from a BlockingCollection.

类似的东西:

var bc = new BlockingCollection<string>();

for ( int i = 0 ; i < 5 ; i++ )
{
    new Thread( () =>
        {
            foreach ( var xml in bc.GetConsumingEnumerable() )
            {
                // do work
            }
        }
    ).Start();
}

bc.Add( xml_1 );
bc.Add( xml_2 );
...
bc.CompleteAdding(); // threads will end when queue is exhausted

这篇关于同时运行x个Web请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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