WebClient/WebRequest threading untangled

WebRequest and its baby sister WebClient behave differently regarding what thread they return on. This is a short post to really clarify what returns where.

Summary

  • WebClient will always return on the UI thread if called from the UI thread
  • WebRequest will always return on a background thread

The investigation

To test this I created a super-simple app that fetches some stuff using WebClient and WebRequest, from the UI and from a background worker.

The code:

And one set of results from running this is:

UI                           Thread is 257753342 (UI)

dispatcher                   Thread is 257753342 (UI)

webrequest from UI           Thread is 255066402 (background)

webclient from UI            Thread is 257753342 (UI)

worker                       Thread is 254411058 (background)

webclient from worker        Thread is 236257614 (background)

webrequest from worker       Thread is 255066402 (background)

As you can see, the WebClient returns on the UI thread when called from the UI thread, but when called from the worker thread – it returns on a background thread.

I hope you feel enlightened – I do Smile

 

This Post Has 2 Comments

Leave a Reply

Close Menu