Starting two WebClient.UploadStringAsync calls sub

2019-07-04 09:27发布

问题:

When calling WebClient.UploadStringAsync twice, without waiting for the WebClient.UploadStringCompleted event, the following exception is thrown:

"WebClient does not support concurrent I/O operations"

Apparently, this is not supported.

The reason for wanting to start multiple HTTP POST requests without having to wait for the previous response to arrive is because of performance; I want to avoid the round trip delay. Is there a workaround for this limitation?

回答1:

You need to use multiple instances of WebClient.

 var wc1 = new WebClient();
 wc1.UploadStringCompleted += (s, args) => {
    // do stuff when first upload completes
 }
 wc1.UploadString(uri1,str1);

 var wc2 = new WebClient();
 wc2.UploadStringCompleted += (s, args) => {
    // do stuff when second upload completes
    // might happen before first has completed
 }
 wc2.UploadString(uri2,str2);