多线程(二)

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...");
        }
    }
}
原文地址:https://www.cnblogs.com/dong897812629/p/3749090.html