Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use HttpClient PostAsync() with threadpool in C#?
    primarykey
    data
    text
    <p>I'm using the following code to post an image to a server.</p> <pre><code>var image= Image.FromFile(@"C:\Image.jpg"); Task&lt;string&gt; upload = Upload(image); upload.Wait(); public static async Task&lt;string&gt; Upload(Image image) { var uriBuilder = new UriBuilder { Host = "somewhere.net", Path = "/path/", Port = 443, Scheme = "https", Query = "process=false" }; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("locale", "en_US"); client.DefaultRequestHeaders.Add("country", "US"); var content = ConvertToHttpContent(image); content.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); using (var mpcontent = new MultipartFormDataContent("--myFakeDividerText--") { {content, "fakeImage", "myFakeImageName.jpg"} } ) { using ( var message = await client.PostAsync(uriBuilder.Uri, mpcontent)) { var input = await message.Content.ReadAsStringAsync(); return "nothing for now"; } } } } </code></pre> <p>I'd like to modify this code to run multiple threads. I've used "ThreadPool.QueueUserWorkItem" before and started to modify the code to leverage it.</p> <pre><code>private void UseThreadPool() { int minWorker, minIOC; ThreadPool.GetMinThreads(out minWorker, out minIOC); ThreadPool.SetMinThreads(1, minIOC); int maxWorker, maxIOC; ThreadPool.GetMaxThreads(out maxWorker, out maxIOC); ThreadPool.SetMinThreads(4, maxIOC); var events = new List&lt;ManualResetEvent&gt;(); foreach (var image in ImageCollection) { var resetEvent = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem( arg =&gt; { var img = Image.FromFile(image.getPath()); Task&lt;string&gt; upload = Upload(img); upload.Wait(); resetEvent.Set(); }); events.Add(resetEvent); if (events.Count &lt;= 0) continue; foreach (ManualResetEvent e in events) e.WaitOne(); } } </code></pre> <p>The problem is that only one thread executes at a time due to the call to "upload.Wait()". So I'm still executing each thread in sequence. It's not clear to me how I can use PostAsync with a thread-pool.</p> <p>How can I post images to a server using multiple threads by tweaking the code above? Is HttpClient PostAsync the best way to do this?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload