Created
June 14, 2019 13:13
-
-
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+
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.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