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

9 篇文章 0 订阅

在这里插入图片描述

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);
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
WPF RichTextBox 控件的滚动条是由系统主题自动渲染的,因此它的颜色会受到系统主题的影响。如果你希望在不同的系统主题下,RichTextBox 控件的滚动条颜色保持一致,可以使用自定义样式。 以下是一个示例样式,它会将 RichTextBox 控件的滚动条颜色设置为红色: ```xml <Style x:Key="CustomRichTextBoxStyle" TargetType="{x:Type RichTextBox}"> <Setter Property="Foreground" Value="White" /> <Setter Property="Background" Value="Black" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type RichTextBox}"> <Grid> <ScrollViewer x:Name="PART_ContentHost" Background="{TemplateBinding Background}" Foreground="{TemplateBinding Foreground}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"> <ScrollViewer.Template> <ControlTemplate TargetType="{x:Type ScrollViewer}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Border Grid.Column="0" Grid.Row="0" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <AdornerDecorator> <ContentPresenter /> </AdornerDecorator> </Border> <ScrollBar x:Name="PART_VerticalScrollBar" Grid.Column="1" Grid.Row="0" Value="{TemplateBinding VerticalOffset}" Maximum="{TemplateBinding ScrollableHeight}" ViewportSize="{TemplateBinding ViewportHeight}" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" /> <ScrollBar x:Name="PART_HorizontalScrollBar" Grid.Column="0" Grid.Row="1" Orientation="Horizontal" Value="{TemplateBinding HorizontalOffset}" Maximum="{TemplateBinding ScrollableWidth}" ViewportSize="{TemplateBinding ViewportWidth}" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" /> </Grid> </ControlTemplate> </ScrollViewer.Template> </ScrollViewer> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> ``` 在上面的样式中,我定义了一个名为 CustomRichTextBoxStyle 的样式,并将其应用于 RichTextBox 控件。该样式使用了一个自定义的 ScrollViewer 模板,并将滚动条的颜色设置为红色。你可以根据需要修改颜色和其他样式属性。 要使用这个样式,只需将 Style 属性设置为 CustomRichTextBoxStyle: ```xml <RichTextBox Style="{StaticResource CustomRichTextBoxStyle}" /> ``` 这样就可以将 RichTextBox 控件的滚动条颜色设置为红色了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王焜棟琦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值