using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace CrossThreadsUpdateUIDemo
{
  public partial class FrmMain : Form
  {
    /// <summary>
    /// 任务队列
    /// </summary>
    private Queue<int> _queueTask = new Queue<int>();
    /// <summary>
    /// 任务循环执行次数
    /// </summary>
    private static int _executeCounter = 0;
 
    private static object locker = new object();
    public FrmMain()
    {
      InitializeComponent();
    }
 
    #region Methods
 
    /// <summary>
    /// 更新UI控件
    /// </summary>
    /// <param name="message"></param>
    private void UpdateLogUI(string message)
    {
      BeginInvoke(new Action(() =>
      {
        lstLog.Items.Insert(0, message);
      }));
    }
 
    /// <summary>
    /// 模拟加载数据
    /// </summary>
    private void LoadData()
    {
      for (int i = 1; i <= 5; i++)
      {
        _queueTask.Enqueue(i);
      }
    }
 
    #endregion
 
    private async void btnStart_Click(object sender, EventArgs e)
    {
      var t = new Thread(new ThreadStart(() => { }));
      t.IsBackground = true;
      t.Start();
      _executeCounter = 0;
      //lstLog.Items.Clear();
      LoadData();
      do
      {
        if (_queueTask == null || _queueTask.Count <= 0)
        {
          break;
        }
        await Task.Run(() =>
        {
          try
          {
            var num = 0;
            _executeCounter++;
            UpdateLogUI(string.Format("开始第{0}次任务,总任务数:{1}...", _executeCounter, _queueTask == null ? 0 : _queueTask.Count));
            var total = _queueTask.Count;
            Parallel.For(0, total, new ParallelOptions { MaxDegreeOfParallelism = 3 }, t =>
            {
              if (num <= 3)
              {
                Thread.Sleep(500);
                num++;
              }
              while (_queueTask.Count > 0)
              {
                var rand = new Random();
                var sleep = rand.Next(500, 5000);
                int task = 0;
                if (_queueTask.Count > 0)
                {
                  lock (_queueTask)
                  {
                    task = _queueTask.Dequeue();
                  }
                }
                UpdateLogUI(string.Format("Task {0} start,Sleep:{1}...", task, sleep));
                Thread.Sleep(sleep);
                UpdateLogUI(string.Format("Task {0} completed.", task));
              }
            });
          }
          catch (Exception ex)
          {
            UpdateLogUI(string.Format("错误:{0}", ex.Message));
          }
        }).ContinueWith(t =>
        {
          UpdateLogUI(string.Format("第{0}次任务执行完成.", _executeCounter));
          if (_executeCounter < 5)
          {
            LoadData();
          }
        });
      }
      while (_queueTask.Count > 0);
      UpdateLogUI("任务完毕");
    }
  }
}