Skip to content

Instantly share code, notes, and snippets.

@illusive-man
Created June 14, 2019 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save illusive-man/23030888d83e64020adbca52876712cc to your computer and use it in GitHub Desktop.
Save illusive-man/23030888d83e64020adbca52876712cc to your computer and use it in GitHub Desktop.
UI Tread non-blocking progress update (done in TAP) C# 5.0+
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
progressBar1.Value = 0;
progressBar1.Maximum = 100;
var progress = new Progress<int>(s => progressBar1.Value = s);
await Task.Factory.StartNew(() => Tasker.LongWork(progress),
TaskCreationOptions.LongRunning);
progressBar1.Value = 100;
}
}
class Tasker
{
public static void LongWork(IProgress<int> progress)
{
// Perform a long running work...
for (var i = 0; i < 100; i++)
{
Task.Delay(100).Wait();
progress.Report(i);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment