How to use HttpWebRequest (.NET) asynchronously?

后端 未结 8 1664
天涯浪人
天涯浪人 2020-11-22 13:56

How can I use HttpWebRequest (.NET, C#) asynchronously?

8条回答
  •  自闭症患者
    2020-11-22 14:36

    I ended up using BackgroundWorker, it is definitely asynchronous unlike some of the above solutions, it handles returning to the GUI thread for you, and it is very easy to understand.

    It is also very easy to handle exceptions, as they end up in the RunWorkerCompleted method, but make sure you read this: Unhandled exceptions in BackgroundWorker

    I used WebClient but obviously you could use HttpWebRequest.GetResponse if you wanted.

    var worker = new BackgroundWorker();
    
    worker.DoWork += (sender, args) => {
        args.Result = new WebClient().DownloadString(settings.test_url);
    };
    
    worker.RunWorkerCompleted += (sender, e) => {
        if (e.Error != null) {
            connectivityLabel.Text = "Error: " + e.Error.Message;
        } else {
            connectivityLabel.Text = "Connectivity OK";
            Log.d("result:" + e.Result);
        }
    };
    
    connectivityLabel.Text = "Testing Connectivity";
    worker.RunWorkerAsync();
    

提交回复
热议问题