多线程创建方式

1、Thread

/// <summary>
/// 线程
/// </summary>
public void ThreadDemo()
{
    // 不带参数
    Thread thread = new Thread(() =>
    {
        Console.WriteLine("开始" + Thread.CurrentThread.ManagedThreadId);
        Thread.Sleep(2000);
        Console.WriteLine("结束");
    });
    Thread thread1 = new Thread(ComplexCompute);
    thread.Start(6);

    Thread th = new Thread(ThreadStartDo);
    th.IsBackground = true;    // 后台启动后,主程序关闭一起关闭。前台程序,主程序关闭仍然执行(默认)
    th.Start();
    // 带参数
    Thread th1 = new Thread(new ParameterizedThreadStart(ThreadStartMsg));
    th1.Start("带参数");
    //匿名方法
    Thread thread2 = new Thread(() =>
    {
        Console.WriteLine("");
    });
    thread.Start();
}
/// <summary>
/// 计算
/// </summary>
/// <param name="count"></param>
public static void ComplexCompute(object count)
{
    int i = 1;
    while (i < (int)count)
    {
        Console.WriteLine("专用线程计时:{0}", i);
        Thread.Sleep(1000);
        i++;
    }
}

2、ThreadStart

/// <summary>
/// ThreadStart案例
/// </summary>
public void ThreadStartDemo()
{
    ThreadStart threadStart = new ThreadStart(ThreadStartDo);
    Thread thread = new Thread(threadStart);
    thread.IsBackground = true;
    thread.Start();
}
/// <summary>
/// do something
/// </summary>
public void ThreadStartDo()
{
    Console.WriteLine("ThreadStart");
}

3、TaskFactory

/// <summary>
/// TaskFactory案例
/// </summary>
public void TaskFactoryDemo()
{
    TaskFactory tf = new TaskFactory();
    tf.StartNew(ThreadStartMsg, "TaskFactory");
}
/// <summary>
///  do something
/// </summary>
/// <param name="msg"></param>
public void ThreadStartMsg(object msg)
{
    Console.WriteLine(msg);
}

4、Task

/// <summary>
/// Task案例
/// </summary>
public void TaskDemo()
{
    //1、第一种方式
    Task.Factory.StartNew(ThreadStartMsg, "Factory");
    //2、第二种方式
    Task.Factory.StartNew(() => ThreadStartMsg("Factory"));
    //3、第三种方式
    Task task = new Task(ThreadStartMsg, "Task");
    task.Start();
    //4、第四种方式
    var task1 = Task.Run(() => ThreadStartMsg("task1"));
    //5、第五种方式
    var task2 = Task.Run(ThreadStartDo);
    //7、第五种方式
    Task t = new Task(new Action<object>(ThreadStartMsg), "12313");
    t.Start();
    //8、第五种方式
    Task<string> treturn = new Task<string>(new Func<object, string>(ThreadReturnMsg), "23242");
    treturn.Start();
}
/// <summary>
///  do something
/// </summary>
/// <param name="msg"></param>
public void ThreadStartMsg(object msg)
{
    Console.WriteLine(msg);
}
/// <summary>
///  do something
/// </summary>
/// <param name="msg"></param>
public void ThreadStartMsg(object msg)
{
    Console.WriteLine(msg);
}
/// <summary>
///  do something
///  参数和返回值
///  task不能有多参数,只能有一个object参数或没有参数
///  下面string是返回值,object是参数
/// </summary>
/// <param name="msg"></param>
public string ThreadReturnMsg(object msg)
{
    Console.WriteLine(msg);
    return msg.ToString();
}

5、ThreadPool

/// <summary>
/// ThreadPool
/// </summary>
public void ThreadPoolDemo()
{
    // 无参数
    ThreadPool.QueueUserWorkItem(ThreadStartMsg, null); // 有参数
    ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolTest), new string[] { "test" });
}
/// <summary>
///  do something
/// </summary>
/// <param name="msg"></param>
public void ThreadStartMsg(object msg)
{
    Console.WriteLine(msg);
}
/// <summary>
/// do something
/// </summary>
/// <param name="state"></param>
public static void ThreadPoolTest(object state)
{
    string[] arry = state as string[];//传过来的参数值
    int workerThreads = 0;
    int CompletionPortThreads = 0;
    ThreadPool.GetMaxThreads(out workerThreads, out CompletionPortThreads);
    Console.WriteLine(DateTime.Now.ToString() + "---" + arry[0] + "--workerThreads=" + workerThreads + "--CompletionPortThreads" + CompletionPortThreads);
}

6、Parallel

/// <summary>
/// Parallel
/// </summary>
public void ParallelDemo()
{
    //1、
     ParallelLoopResult result = Parallel.For(0, 10, new ParallelOptions()
     {
         MaxDegreeOfParallelism = 10
     }, i =>
     {
         Console.WriteLine("迭代次数:{0},任务ID:{1},线程ID:{2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
         Thread.Sleep(10);
      });
      Console.WriteLine("是否完成:{0}", result.IsCompleted);
      Console.WriteLine("最低迭代:{0}", result.LowestBreakIteration);
    //2、
    // 数组遍历
    string[] data = { "str1", "str2", "str3" };
    ParallelLoopResult result2 = Parallel.ForEach<string>(data, str =>
    {
        Console.WriteLine(str);
    });
    Console.WriteLine("是否完成:{0}", result2.IsCompleted);
    Console.WriteLine("最低迭代:{0}", result2.LowestBreakIteration);
    //3、
    // 多任务制定    Parallel.Invoke(Func1, Func2, Func3);
    Parallel.Invoke(() =>
    {
        Thread.Sleep(100);
        Console.WriteLine("method1");
    }, () =>
    {
       Thread.Sleep(10);  
       Console.WriteLine("method2");
    });
}

 

posted @ 2023-01-05 14:42  木头马尾、、、  阅读(21)  评论(0编辑  收藏  举报