Async winform process that reports progress

This is mostly put together from examples I pulled online, but I got it working and I figure other people could use it as well. This has a Form1 form and a ProgressForm form put I tried to put all the code together for this post.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestingAsync
{ 
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Console.WriteLine("Starting..");
            var mgr = new Manager();
            mgr.GoAsync(this);
            MessageBox.Show("END");
        }
    }

    class Manager
    {
        private static ProgressForm _progressForm;

        public async Task GoAsync(Form owner )
        {
            //var owner = new Win32Window(Process.GetCurrentProcess().MainWindowHandle);
            _progressForm = new ProgressForm();
            _progressForm.Show(owner);

            var progress = new Progress<int>(value => _progressForm.UpdateProgress(value));
            await Go(progress);

            _progressForm.Hide();
        }

        private Task<bool> Go(IProgress<int> progress)
        {
            return Task.Run(() =>
            {
                var job = new LongJob();
                job.Spin(progress);
                return true;
            });
        }
    }

    class LongJob
    {
        public void Spin(IProgress<int> progress)
        {
            for (var i = 1; i <= 100; i++)
            {
                Thread.Sleep(25);
                if (progress != null)
                {
                    progress.Report(i);
                }
            }
        }
    }


}

Advertisements