当前位置: 代码网 > it编程>编程语言>C# > 详解C#如何解决程序卡顿的问题(多线程初步学习)

详解C#如何解决程序卡顿的问题(多线程初步学习)

2024年05月26日 C# 我要评论
正文不带参数的多线程实现第一步 建立控制台应用第二步 引用system.threading.threadusing system.threading;在 c# 中,system.threading.t

正文

不带参数的多线程实现

第一步 建立控制台应用

在这里插入图片描述

第二步 引用system.threading.thread

using system.threading;

在 c# 中,system.threading.thread 类用于线程的工作。它允许创建并访问多线程应用程序中的单个线程。进程中第一个被执行的线程称为主线程。

第三步:完成代码

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using system.threading;

namespace 多线程test
{
    class program
    {
        static void main(string[] args)
        {
            int num = 100;
            for (int i = 0; i < num; i++)
            {
                //无参的多线程
                noparmathread();
               
            }
        }
         private static void startthread()

        {
            console.writeline("------开始了新线程------");
            thread.sleep(2000);//wait
            console.writeline("------线程结束------");
        }

        /// <summary>
        ///不需要传递参数
        /// </summary>
        private static void noparmathread()
        {
            threadstart threadstart = new threadstart(startthread);
            var thread = new thread(threadstart);
            thread.start();//开始线程
        }
    }
}

运行结果

在这里插入图片描述

拓展:c#多线程刷新界面卡死测试

背景

在上位机程序开发过程中,不可避免的会用到多线程,如处理socket通信、plc读取、界面数据实时刷新等。在某个项目中由于开启的线程很多,出现了不定期界面卡死状况,但后台线程还在运行,日志还在输出。为了解决这个问题,特写了模拟程序进行问题复现。顺便把过程分享一下。

要点

1、区分control.begininvoke和control.invoke的用法

2、区分system.timers.timer、system.threading.threadpool、system.threading.thread

demo

创建一个winform应用程序,把工程属性的输出类型设置为控制台应用程序,方便运行时查看日志。

关键代码

basicinvoker

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using system.windows.forms;

namespace winapp
{
    /// <summary>
    /// 调用器
    /// </summary>
    public class basicinvoker
    {
        public delegate void invoke(); 

        private form form = null;
        private textbox txt = null;
        private object value = string.empty;

        public basicinvoker(form form, textbox txt, object value)
        {
            this.form = form;
            this.txt = txt;
            this.value = value;
        }

        public void setvalue()
        {
            if (this.form != null && !this.form.isdisposed)
            {
                if (this.form.invokerequired)
                {
                    delegate d = new invoke(this.dowork);
                    try
                    {
                        this.form.invoke(d, null);
                        //this.form.begininvoke(d);
                    }
                    catch(exception ex)
                    {
                        console.writeline(ex.message);
                    }
                }
                else
                {
                    this.dowork();
                }
            }
        }

        public void dowork()
        {
            if (this.txt != null)
            {
                this.txt.text = this.value.tostring();
                console.writeline(string.format("{0:yyyy-mm-dd hh:mm:ss.fff}", datetime.now) + "  " +  this.value.tostring() + "...1");
                system.threading.thread.sleep(200);
                console.writeline(string.format("{0:yyyy-mm-dd hh:mm:ss.fff}", datetime.now) + "  " + this.value.tostring() + "...2");
            }
        }
    }
}

frmtest

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.threading.tasks;
using system.windows.forms;

namespace winapp
{
    public partial class frmtester : form
    {
        #region 变量定义

        private system.timers.timer timer1 = null;
        private system.timers.timer timer2 = null;
        private system.timers.timer timer3 = null;

        private system.threading.thread thread1 = null;
        private system.threading.thread thread2 = null;
        private system.threading.thread thread3 = null;

        #endregion

        #region 构造方法

        public frmtester()
        {
            initializecomponent();
        }

        #endregion

        #region 事件处理

        private void form1_load(object sender, eventargs e)
        {
            
        }

        private void button1_click(object sender, eventargs e)
        {
            if (timer1 == null)
            {
                timer1 = new system.timers.timer();
                timer1.interval = 500;
                timer1.elapsed += t1_elapsed;
                timer1.start();
            }
        }

        private void button2_click(object sender, eventargs e)
        {
            if (timer2 == null)
            {
                timer2 = new system.timers.timer();
                timer2.interval = 500;
                timer2.elapsed += t2_elapsed;
                timer2.start();
            }
        }        

        private void button3_click(object sender, eventargs e)
        {
            if (timer3 == null)
            {
                timer3 = new system.timers.timer();
                timer3.interval = 500;
                timer3.elapsed += t3_elapsed;
                timer3.start();
            }
        }

        private void button4_click(object sender, eventargs e)
        {
            system.threading.threadpool.queueuserworkitem(new system.threading.waitcallback(this.callback1));
        }

        private void button5_click(object sender, eventargs e)
        {
            system.threading.threadpool.queueuserworkitem(new system.threading.waitcallback(this.callback2));
        }

        private void button6_click(object sender, eventargs e)
        {
            system.threading.threadpool.queueuserworkitem(new system.threading.waitcallback(this.callback3));
        }

        private void button7_click(object sender, eventargs e)
        {
            if (this.thread1 == null)
            {
                this.thread1 = new system.threading.thread(new system.threading.threadstart(this.callback1));
                this.thread1.start();
            }
        }

        private void button8_click(object sender, eventargs e)
        {
            if (this.thread2 == null)
            {
                this.thread2 = new system.threading.thread(new system.threading.threadstart(this.callback2));
                this.thread2.start();
            }
        }

        private void button9_click(object sender, eventargs e)
        {
            if (this.thread3 == null)
            {
                this.thread3 = new system.threading.thread(new system.threading.threadstart(this.callback3));
                this.thread3.start();
            }
        }

        private void form1_formclosing(object sender, formclosingeventargs e)
        {
            console.writeline("formclosing...");
            
            if (this.timer1 != null)
            {
                this.timer1.stop();
                this.timer1.dispose();
            }
            if (this.timer2 != null)
            {
                this.timer2.stop();
                this.timer2.dispose();
            }
            if (this.timer3 != null)
            {
                this.timer3.stop();
                this.timer3.dispose();
            }

            if (this.thread1 != null)
            {
                //if (this.thread1.threadstate == system.threading.threadstate.running)
                {
                    this.thread1.abort();
                }
            }

            if (this.thread2 != null)
            {
                //if (this.thread2.threadstate == system.threading.threadstate.running)
                {
                    this.thread2.abort();
                }
            }

            if (this.thread3 != null)
            {
                //if (this.thread3.threadstate == system.threading.threadstate.running)
                {
                    this.thread3.abort();
                }
            }
        }

        private void form1_formclosed(object sender, formclosedeventargs e)
        {
            console.writeline("formclosed...");
        }  

        #endregion

        #region 定时处理方法定义

        private void t1_elapsed(object sender, system.timers.elapsedeventargs e)
        {
            //lock(global.publicvar.instance.locker1)
            lock (string.empty)
            {
                basicinvoker invoker = new basicinvoker(this, this.textbox1, guid.newguid().tostring());
                invoker.setvalue();
            }
        }

        private void t2_elapsed(object sender, system.timers.elapsedeventargs e)
        {
            lock (global.publicvar.instance.locker1)
            lock (string.empty)
            {
                basicinvoker invoker = new basicinvoker(this, this.textbox1, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
                invoker.setvalue();
            }
        }

        private void t3_elapsed(object sender, system.timers.elapsedeventargs e)
        {
            //lock (global.publicvar.instance.locker1)
            lock (string.empty)
            {
                basicinvoker invoker = new basicinvoker(this, this.textbox1, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
                invoker.setvalue();
            }
        }

        public void callback1(object state)
        {
            while(true)
            {
                //lock (global.publicvar.instance.locker1)
                lock(string.empty)
                {
                    basicinvoker invoker = new basicinvoker(this, this.textbox1, guid.newguid().tostring());
                    invoker.setvalue();
                }
                system.threading.thread.sleep(500);
            }
        }

        public void callback2(object state)
        {
            while (true)
            {
                //lock (global.publicvar.instance.locker1)
                lock(string.empty)
                {
                    basicinvoker invoker = new basicinvoker(this, this.textbox1, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
                    invoker.setvalue();
                }
                system.threading.thread.sleep(500);
            }
        }

        public void callback3(object state)
        {
            while (true)
            {
                //lock (global.publicvar.instance.locker1)
                lock(string.empty)
                {
                    basicinvoker invoker = new basicinvoker(this, this.textbox1, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
                    invoker.setvalue();
                }
                system.threading.thread.sleep(500);
            }
        }

        public void callback1()
        {
            while (true)
            {
                //lock (global.publicvar.instance.locker1)
                lock (string.empty)
                {
                    basicinvoker invoker = new basicinvoker(this, this.textbox1, guid.newguid().tostring());
                    invoker.setvalue();
                }
                system.threading.thread.sleep(500);
            }
        }

        public void callback2()
        {
            while (true)
            {
                //lock (global.publicvar.instance.locker1)
                lock (string.empty)
                {
                    basicinvoker invoker = new basicinvoker(this, this.textbox1, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
                    invoker.setvalue();
                }
                system.threading.thread.sleep(500);
            }
        }

        public void callback3()
        {
            while (true)
            {
                //lock (global.publicvar.instance.locker1)
                lock (string.empty)
                {
                    basicinvoker invoker = new basicinvoker(this, this.textbox1, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
                    invoker.setvalue();
                }
                system.threading.thread.sleep(500);
            }
        }

        #endregion
    }
}

运行图:

运行结果:

一、使用control.begininvoke的情况

public void setvalue()
        {
            if (this.form != null && !this.form.isdisposed)
            {
                if (this.form.invokerequired)
                {
                    delegate d = new invoke(this.dowork);
                    try
                    {
                        //this.form.invoke(d, null);
                        this.form.begininvoke(d);
                    }
                    catch(exception ex)
                    {
                        console.writeline(ex.message);
                    }
                }
                else
                {
                    this.dowork();
                }
            }
        }

1.1、system.timers.timer开启2以上很快界面卡死,日志正常输出。

1.2、system.threading.threadpool开启3个时,运行一会界面卡死,日志正常输出。

1.3、system.threading.thread开启3个时,运行一会界面卡死,日志正常输出。

二、使用control.invoke的情况

public void setvalue()
        {
            if (this.form != null && !this.form.isdisposed)
            {
                if (this.form.invokerequired)
                {
                    delegate d = new invoke(this.dowork);
                    try
                    {
                        this.form.invoke(d, null);
                        //this.form.begininvoke(d);
                    }
                    catch(exception ex)
                    {
                        console.writeline(ex.message);
                    }
                }
                else
                {
                    this.dowork();
                }
            }
        }

2.1、system.timers.timer开启3个时很快界面卡死,日志正常输出。

2.2、system.threading.threadpool开启3个时,界面正常操作,日志正常输出。

2.3、system.threading.thread开启3个时,界面正常操作,日志正常输出。

测试总结:

1、system.threading.threadpool与system.threading.thread运行效果基本相同。

2、在多线程刷新界面时尽量通过control.invoke调用委托实现。

小结

到此这篇关于详解c#如何解决程序卡顿的问题(多线程初步学习)的文章就介绍到这了,更多相关c#解决程序卡顿内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com