zoukankan      html  css  js  c++  java
  • 多线程(二)

    1.线程池

    线程池维护一个请求队列,线程池的代码从队列提取任务,然后委派给线程池的一个线程执行,线程执行完不会被立即销毁,这样既可以在后台执行任务,又可以减少线程创建和销毁所带来的开销

    线程池线程默认为后台线程(IsBackground)

    namespace Test
    {
        class Program
        {
            static void Main(string[] args)
            {
                //将工作项加入到线程池队列中,这里可以传递一个线程参数
                ThreadPool.QueueUserWorkItem(TestMethod, "Hello");
                Console.ReadKey();
            }
    
            public static void TestMethod(object data)
            {
                string datastr = data as string;
                Console.WriteLine(datastr);
            }
        }
    }

    2.委托异步执行

     委托的异步调用:BeginInvoke() 和 EndInvoke()

    /**/
    using System.Threading;
    
    namespace 多线程
    {
        public delegate string MyDelegate(object data);
        class Program
        {
            static void Main(string[] args)
            {
                MyDelegate mDelegate = new MyDelegate(TestMethod);
                IAsyncResult result = mDelegate.BeginInvoke("Thread Param", TestCallback, "Callback Param");
                var strResult = mDelegate.EndInvoke(result);
                Console.ReadKey();
            }
    
            /// <summary>
            /// 线程函数
            /// </summary>
            /// <param name="data"></param>
            /// <returns></returns>
            public static string TestMethod(object data)
            {
                var strData = data as string;
                return strData;
                
            }
    
            /// <summary>
            /// 异步回调函数
            /// </summary>
            /// <param name="data"></param>
            public static void TestCallback(IAsyncResult data)
            {
                Console.WriteLine(data.AsyncState);
            }
           
        }
    }

    3.多线程计时器

    using System.Timers;//多线程计时器
    namespace 定时器
    {
        class Program
        {
            static void Main(string[] args)
            {
                Timer tmr = new Timer();
                tmr.Interval = 1000;
                tmr.Elapsed+=tmr_Elapsed;
                tmr.Start();
                Console.ReadLine();
                tmr.Stop();
                tmr.AutoReset = true;////设置是执行一次(false)还是一直执行(true) 
            }
    
            private static void tmr_Elapsed(object sender, ElapsedEventArgs e)
            {
                Console.WriteLine("Tick...");
            }
        }
    }
  • 相关阅读:
    vue hover如何触发事件?
    防止 window.open 被拦截
    input输入框change和blur事件区别
    神马?使用JS直接上传并预览粘贴板的图片?
    删除设备与驱动器中百度网盘图标
    枚举类字典代码 草稿
    中文转换成阿拉伯数字
    Java对象与类中的一个小练习
    正向代理和反向代理
    MySQL教程126-MySQL事务隔离级别
  • 原文地址:https://www.cnblogs.com/dong897812629/p/3749090.html
Copyright © 2011-2022 走看看