zoukankan      html  css  js  c++  java
  • 记一下今天上下班学的Thread

    1 Thread 默认为前台线程,即主程序退出后,线程还可以继续(曾经就掉入这个坑中,使用两线程分别进行UDP收发,结果发线程结束了退出方法,收线程还在继续)

    2 Thread 没有可以暂停,可以重新启动,但是没有结束方法,使用Abort()方法强制销毁会抛异常。

    3 线程的等待用Join()实现

                List<Thread> threadList = new List<Thread>();
                for (int i = 0; i < 5; i++)
                {
                    string name = string.Format("btnThread_Click_{0}", i);
                    ThreadStart method = () => this.TestThread(name);
                    Thread thread = new Thread(method);//1 默认前台线程:程序退出后,计算任务会继续
                    thread.IsBackground = true;//2 后台线程:程序退出,计算立即结束
                    thread.Start();
                    threadList.Add(thread);
    
                    //ParameterizedThreadStart method = o => this.TestThread(o.ToString());
                    //Thread thread = new Thread(method);
                    //thread.Start(name);
                }
    
                foreach (Thread thread in threadList)
                {
                    thread.Join();
                }

    4 Thread 也没有回调和返回值,如果使用回调函数,需要手动实现

            /// <summary>
            /// 使用Thread 完成多线程回调
            /// </summary>
            /// <param name="method">要多线程执行的任务</param>
            /// <param name="callback">回调执行的任务</param>
    
            private void ThreadBeginInvoke(ThreadStart method, Action callback)
            {
                ThreadStart methodAll = new ThreadStart(() =>
                {
                    method.Invoke();
                    callback.Invoke();
                });
                Thread thread = new Thread(methodAll);
                thread.Start();
            }
    将偷懒进行到极致,是一个程序员的基本素养
  • 相关阅读:
    透明度问题解决方案
    不得不去奋斗的原因
    未来的你肯定会感谢现在努力的你
    前端学习参考
    js仿京东轮播图效果
    hyper容器网络相关源码分析
    利用setns()将进程加入一个新的network namespace
    frakti && RunPodSandbox 源码分析
    Makefile 编写 tips
    《In Search of an Understandable Consensus Algorithm》翻译
  • 原文地址:https://www.cnblogs.com/bamboo-zhang/p/9142680.html
Copyright © 2011-2022 走看看