Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kungfux
Last active December 29, 2020 09:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kungfux/a5dc4a41622348c062d3854c7653b577 to your computer and use it in GitHub Desktop.
Save kungfux/a5dc4a41622348c062d3854c7653b577 to your computer and use it in GitHub Desktop.
C# async await example
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