Await - Async in C#

  await - async  in C#

WPF

Sample1:  without UI controll
var webclient = new WebClient();
var downThread = new Thread( ()=> {

var result = webclient.DownloadString("http://www.google.com");
MessageBox.Show(result);

});
downThread.Start();

Sample2: still without UI controll.
runButton.IsEnabled= false;
var webclient = new WebClient();
var downThread = new Thread( ()=> {

var result = webclient.DownloadString("http://www.google.com");
MessageBox.Show(result);

});
downThread.Start();
runButton.IsEnabled= true;

Sample3: error.
runButton.IsEnabled= false;

var webclient = new WebClient();
var downThread = new Thread( ()=> {

    var result = webclient.DownloadString("http://www.google.com");
    MessageBox.Show(result);
    runButton.IsEnabled= true;  // is going to crash. error.

});
downThread.Start();

Sample4:Dispatcher.Invoke
runButton.IsEnabled= false;

var webclient = new WebClient();
var downThread = new Thread( ()=> {

    var result = webclient.DownloadString("http://www.google.com");
    MessageBox.Show(result);
    Dispatcher.Invoke(() => {
        runButton.IsEnabled= true; 
    });

});
downThread.Start();

Log : from :
https://www.youtube.com/watch?v=MR-MuIBc9xM&list=PLkjO-gN54obCIaFAy-HNL44mO-DjSk7tA&index=9

Sample5:  Await & Async
runButton.IsEnabled= false;

var webclient = new WebClient();
var result = awaot webclient.DownloadStringTaskAsync("http://www.google.com");
MessageBox.Show(result);
downThread.Start();

Async function can't block the running thread on where asysnc function runs.
Async function returns a task immediately.
public async Task Save(){
  var wc = new WebClient():
  var result = await wc.DownloadStringTaskAsync("http://google.com");
  await Task.Run(()=>{File.WriteAllText("D://test.txt",result);});
}

var task = Save();  // immediately return;
await task;            // run the content of async function.





评论

此博客中的热门博文

XML, XSL, HTML

Input in element.eleme.io

Data URI是由RFC 2397 ACE