-
-
Save benschg/4d8b11bb4a6f1a9b99995daf5226a5e1 to your computer and use it in GitHub Desktop.
C# async await example
This file contains hidden or 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
using System; | |
using System.Windows.Forms; | |
using System.Threading; | |
using System.Threading.Tasks; | |
class Program | |
{ | |
[STAThread] | |
public static void Main() | |
{ | |
Application.EnableVisualStyles(); | |
Application.SetCompatibleTextRenderingDefault(false); | |
Application.Run(new Form1()); | |
} | |
public class Form1: Form | |
{ | |
public Form1() | |
{ | |
b1 = new Button(); | |
b1.Text = "Perform long operation"; | |
b1.Dock = DockStyle.Top; | |
b1.Click += new EventHandler(B1_Click); | |
Controls.Add(b1); | |
b2 = new Button(); | |
b2.Text = "Show Message"; | |
b2.Dock = DockStyle.Top; | |
b2.Click += new EventHandler(B2_Click); | |
Controls.Add(b2); | |
l = new Label(); | |
l.Text = "Wait"; | |
l.Dock = DockStyle.Bottom; | |
Controls.Add(l); | |
} | |
Button b1; | |
Button b2; | |
Label l; | |
private void B1_Click(object sender, EventArgs e) | |
{ | |
DoLongOperation(); | |
} | |
private void B2_Click(object sender, EventArgs e) | |
{ | |
MessageBox.Show("message"); | |
} | |
private async void DoLongOperation() | |
{ | |
b1.Enabled = false; | |
l.Text = "Doing..."; | |
var result = await Task<string>.Factory.StartNew(() => | |
{ | |
Thread.Sleep(5000); | |
return "Done"; | |
}); | |
l.Text = result; | |
b1.Enabled = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment