Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async WebClient not truly Async?

I have created an Asynchronous WebClient request inside a class as follows:

public class Downstream
    {
        public bool StartDownstream()
        {
            WebClient client = new WebClient();

            client.Headers.Add("user-agent", "Mozilla/4.0 [...]");
            client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
            try
            {

                byte[] postArray = Encoding.UTF8.GetBytes("somevar=foo&someothervar=bar");
                Uri uri = new Uri("http://www.examplesite.com/somepage.php");

                client.UploadDataCompleted += 
                new UploadDataCompletedEventHandler(client_UploadDataCompleted);
                client.UploadDataAsync(uri, postArray);
            }
            catch (WebException e)
            {
                MessageBox.Show("A regular Web Exception");
            }
            catch (NotSupportedException ne)
            {
                MessageBox.Show("A super Web Exception");
            }
            return true;
        }

        void client_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            MessageBox.Show("The WebClient request completed");
        }
    }

I then create a new instance of the class and run the method here:

Downstream Downstream1 = new Downstream();
Downstream1.StartDownstream();

When I do so, the thread that the form is running on seems to hang until the WebClient gets a response back. Why is this? I have used the UploadDataAsync method so should it not be Asynchronous?

Edit:

This is my call stack:

    [External Code] 
>   Arcturus.exe!Arcturus.Downstream.StartDownstream() Line 36 + 0x18 bytes C#
    Arcturus.exe!Arcturus.MainWindow.btnLogin_Click(object sender, System.Windows.RoutedEventArgs e) Line 111 + 0x12 bytes  C#
    [External Code]

This is all that happens when I run my application, just hanging on the StartDownstream() and client.UploadDataAsync(uri, postArray); methods.

like image 489
Joel Kennedy Avatar asked Nov 14 '22 03:11

Joel Kennedy


1 Answers

My problem I had was to do with the WebClient using the same thread as the UI, regardless of it being Async or not. I decided to use a BackgroundWorker instead.

Thanks for the answers!

like image 65
Joel Kennedy Avatar answered Dec 15 '22 05:12

Joel Kennedy