Task任務設置取消使用,RichTextBox設置消息顏色顯示,RichTextBox消息跨線程顯示

Task任務設置取消使用,RichTextBox設置消息顏色顯示,RichTextBox消息跨線程顯示

Task設置取消任務,主要用

//取消任务标志
CancellationTokenSource cancellation = new CancellationTokenSource();
var task_run = Task.Run(() => SyncData(cancellation.Token), cancellation.Token);
//發送取消請求
cancellation.Cancel();
//通知立馬執行取消,必須此行代碼
cancellation.Token.ThrowIfCancellationRequested();

private void SyncData(CancellationToken cancellationToken)
{
	while (!cancellation.Token.IsCancellationRequested)
	{
		//代碼邏輯
	}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Pisen.Data;
using Pisen.ProductCenter.DataSyncCommon;
using Pisen.ProductCenter.TaskService;
using Pisen.ProductCenter.TaskService.Core;
using Pisen.ProductCenter.TaskService.Service.Model;

namespace Pisen.ProductCenter.TaskServiceWinFormLogTest
{
    public partial class TaskServices : Form
    {

        /// <summary>
        /// 执行同步的任务
        /// </summary>
        List<Task> taskList = new List<Task>(50);

        /// <summary>
        ///當前任務id
        /// </summary>
        int taskId = 0;

        public TaskServices()
        {
            InitializeComponent();
            richTextBox1.ReadOnly = true;
            richTextBox1.UseWaitCursor = false;
            richTextBox1.BackColor = Color.White;
            richTextBox1.ShortcutsEnabled = false;
            btnStop.Enabled = false;
        }

        /// <summary>
        /// 同步数据
        /// </summary>
        private void SyncData(CancellationToken cancellationToken)
        {
            ShowMsg("开始同步...");
            DataSyncProcess syncService = new DataSyncProcess();
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    ShowMsg($"任務{taskId}开始查询待同步数据...");
                    List<SynchronizationLog> list = syncService.initQuery();
                    if (list == null || list.Count == 0)
                    {
                        ShowMsg("暂无需要同步的数据", Color.Black);
                        continue;
                    }
                    ShowMsg("查詢到的條數" + list.Count);
                    foreach (var item in list)
                    {
                        ShowMsg("執行同步...");
                        var result = SyncFactory.SyncData(item);
                        if (result.Status == false)
                        {
                            ShowMsg(string.Format("{0} {1}", item.DataSysNo, result.Message), Color.Red);
                        }
                        else
                        {
                            ShowMsg(string.Format("{0} 同步成功!", item.DataSysNo), Color.Black);
                        }
                    }
                    ShowMsg("本次同步结束", Color.Blue);
                }
                catch (Exception ex)
                {
                    ShowMsg("同步异常," + ex.ToString(), Color.Red);
                }
                finally
                {
                    ShowMsg("休息30秒后再同步...", Color.Black);
                    //30秒
                    Thread.Sleep(30 * 1000);
                }
            }
        }

        /// <summary>
        /// 打印執行步驟消息到窗體
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="color"></param>     
        public void ShowMsg(string msg, params Color[] color)
        {
            try
            {
                //本地日誌記錄
                Task.Run(() => LogHelpter.AddLog("任務" + taskId + "," + msg));
                string msg2 = string.Format("{0}  {1}{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msg, System.Environment.NewLine);
                richTextBox1.BeginInvoke(new Action(() =>
                {
                    richTextBox1.SelectionStart = richTextBox1.TextLength;
                    richTextBox1.ScrollToCaret();
                    if (richTextBox1.Lines.Length > 1001)
                    {
                        string[] arr = richTextBox1.Lines;
                        this.richTextBox1.Lines = arr.Skip(1).ToArray();
                    }
                    if (color.Length > 0)
                    {
                        //當前這條消息改變顏色,顏色設置
                        this.richTextBox1.SelectionColor = color[0];
                    }
                    richTextBox1.AppendText(msg2);
                }));
            }
            catch (Exception ex)
            {
                Task.Run(() => LogHelpter.AddLog("任務" + taskId + "," + ex.ToString()));
            }
        }

        //开始
        private void btnStart_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = false;
            btnStop.Enabled = true;
            var cancellation = new CancellationTokenSource();
            Action<object> action = (w) =>
            {
                SyncData(cancellation.Token);
            };
            var task_run = Task.Factory.StartNew(action, cancellation, cancellation.Token);
            taskId = task_run.Id;
            LogHelpter.AddLog($"任務{taskId}開始...");
            taskList.Add(task_run);
        }


        //停止
        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                btnStart.Enabled = true;
                btnStop.Enabled = false;
                CancellationTokenSource cancellation = taskList.Last().AsyncState as CancellationTokenSource;
                cancellation.Cancel();
                try
                {
                    cancellation.Token.ThrowIfCancellationRequested();
                }
                catch (Exception ex)
                {
                    //ShowMsg("任务消息" + ex.ToString(), Color.Red);
                    ShowMsg($"任务{taskId}已取消", Color.Blue);
                }
                Task.Run(
                  () =>
                  {
                      int taskId2 = taskId;
                      var taskStop2 = taskList.Find(w => w.Id == taskId2);
                      if (taskStop2 != null)
                      {
                          taskStop2.Wait();
                          if (taskStop2.IsCompleted)
                          {
                              taskStop2.Dispose();
                              LogHelpter.AddLog($"任務{taskId2}已釋放");
                          }
                      }
                  });
            }
            catch (Exception ex)
            {
                ShowMsg(ex.ToString(), Color.Red);
            }
        }
    }
}