c#中线程使用:跨线程访问组件,线程的开启与停止

c#中Delegate是一个类,它是所有delegate类的基类,而delegate和class一样是一个关键字,可以定义函数的类别。事件和委托一样,其实现是队列,只不过事件是有访问性的委托。声明方式
public delegate void Mydel(int a); public event Mydel myEvent; Mydel mydel1=t.fun; Mydel mydel2=new Mydel(t.fun); myEvent+=t.fun;

跨线程访问组件

using System;
using System.Collections.Generic;
using System.Drawing.Text;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2.ThreadTool
{
    public class SafeInvoke
    {
        private delegate void TextShowDelegate(Control control,String text);
        public static void invoke(Control control, String text)
        {
            if (control.InvokeRequired)
            {
                control.BeginInvoke(new TextShowDelegate(textShow),new object[] {control, text });
            }
            else
            {
                control.Text = text;
            }
        }

        private static void textShow(Control control,String text)
        {
            control.Text = text;
        }
    }
}

线程的开启与停止(线程、线程池、异步),简单的加锁并发访问

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp2.ThreadTool;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {


        public Thread thread1;
        // 工单状态
        public int workOrderState = 0;
        private static readonly Object workOrderLock = new Object();

        public volatile bool thread1RunState = false;
        public volatile bool threadPoolRunState = false;
        public volatile bool taskRunState = false;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            // 1 跨线程访问组件 报错
            //thread1 = new Thread(() => {
            //    this.label1.Text = "123";
            // });
            if (thread1 == null || !thread1.IsAlive)
            {
                thread1 = new Thread(async () =>
                {
                    try
                    {
                        thread1RunState = true;
                        // 使用volatile关键字控制线程运行
                        while (thread1RunState)
                        {
                            Random rangdom = new Random();
                            lock (workOrderLock)
                            {
                                workOrderState = rangdom.Next(3, 999);
                            }
                            SafeInvoke.invoke(this.label1, "thread开启了,工单状态" + workOrderState);
                            //Thread.Sleep(500);
                            await Task.Delay(500);
                        }
                    }
                    catch (ThreadInterruptedException E)
                    {
                    }
                    finally
                    {
                        SafeInvoke.invoke(this.label1, "thread关闭了");
                    }
                });
                // 2  跨线程访问组件    
                thread1.Start();
            }


            if (!threadPoolRunState)
            {
                // 线程池
                WaitCallback waitCallback = new WaitCallback(async x =>
                {
                    try
                    {
                        threadPoolRunState = true;
                        // 使用volatile关键字控制线程运行
                        while (threadPoolRunState)
                        {
                            Random rangdom = new Random();
                            lock (workOrderLock)
                            {
                                workOrderState = rangdom.Next(3, 999);
                            }
                            SafeInvoke.invoke(this.label2, "thread开启了,工单状态" + workOrderState);
                            await Task.Delay(500);// 不会阻塞线程
                                                  //Thread.Sleep(500);
                        }
                    }
                    catch (ThreadInterruptedException E)
                    {

                    }
                    finally
                    {
                        SafeInvoke.invoke(this.label2, "thread关闭了");

                    }
                });
                //ThreadPool.QueueUserWorkItem(x => { SafeInvoke.invoke(this.label1, "456"); });
                ThreadPool.QueueUserWorkItem(waitCallback);
            }

            // 3. task 异步线程池 
            // 需要一个前台线程。
            // 需要具有特定优先级的线程。
            // 拥有会导致线程长时间阻塞的任务。 线程池具有最大线程数,因此大量被阻塞的线程池线程可能会阻止任务启动,
            // 应用中出现过此种情况,当一个任务错误记录日志疯狂开线程,会导致线程池中其他keepware采集不能正常执行。
            // 需具有与线程关联的稳定标识,或需将一个线程专用于一项任务。
            if (!taskRunState)
            {
                Task.Run(async () =>
                {
                    try
                    {
                        taskRunState = true;
                        // 使用volatile关键字控制线程运行
                        while (taskRunState)
                        {
                            Random rangdom = new Random();
                            lock (workOrderLock)
                            {
                                workOrderState = rangdom.Next(3, 999);
                            }
                            SafeInvoke.invoke(this.label3, "thread开启了,工单状态" + workOrderState);
                            await Task.Delay(500);
                             //Thread.Sleep(500);
                         }
                    }
                    catch (ThreadInterruptedException E)
                    {
                    }
                    finally
                    {
                        SafeInvoke.invoke(this.label3, "thread关闭了");
                    }

                }).ConfigureAwait(false);
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            thread1RunState = false;
            thread1.Interrupt();![在这里插入图片描述](https://img-blog.csdnimg.cn/20200725094656133.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zNzU0OTQ1OA==,size_16,color_FFFFFF,t_70#pic_center)

            threadPoolRunState = false;
            taskRunState = false;

        }
    }
}

点击开启按钮
c#中线程使用:跨线程访问组件,线程的开启与停止_第1张图片
c#中线程使用:跨线程访问组件,线程的开启与停止_第2张图片

点击关闭按钮
c#中线程使用:跨线程访问组件,线程的开启与停止_第3张图片

你可能感兴趣的:(c#,c#,多线程,thread)