Created
September 28, 2011 16:49
-
-
Save ipa/1248457 to your computer and use it in GitHub Desktop.
async in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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