Skip to content

Instantly share code, notes, and snippets.

@ipa
Created September 28, 2011 16:49
Show Gist options
  • Save ipa/1248457 to your computer and use it in GitHub Desktop.
Save ipa/1248457 to your computer and use it in GitHub Desktop.
async in C#
// synchronous way
private void Synchronous()
{
WebClient proxy = new WebClient();
string result = proxy.DownloadString("http://tel.search.ch/?wo=luzern");
}
// with backgroundworkers
private void Background()
{
this.ClearText();
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
try
{
worker.RunWorkerAsync();
}
catch (Exception ex)
{
// ...
}
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
// ...
}
this.txtWebResult.Text = e.Result.ToString();
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
WebClient proxy = new WebClient();
string result = string.Empty;
try
{
result = proxy.DownloadString("http://tel.search.ch/?wo=luzern");
}
catch (Exception ex)
{
// ...
}
e.Result = result;
}
// with async
private async void Async()
{
this.ClearText();
WebClient proxy = new WebClient();
string result = string.Empty;
try
{
result = await proxy.DownloadStringTaskAsync("http://tel.search.ch/?wo=luzern");
}
catch (Exception ex)
{
// ...
}
this.txtWebResult.Text = result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment