当前位置:网站首页 > 创业 > 正文

【源码】c#如何使用多线程

0 张子豪 张子豪 2025-10-12 07:18 1

c#若何利用多线程,简单几步,让你轻松几步解决。

东西/原料

  • IDE

方式/步调

  1. 1

    1.  打开vs或者其他IDE, 建立节制台项目如下

  2. 2

    2. 无参数的多线程。在Program.cs文件里面写入如下代码

    class Program

    {

    static void Main(string[] args)

    {

    int num = 2;

    for ( int i =0; i < num; i++)

    {

    noParmaThread();

    }

    }

    private static void StartThread()

    {

    Console.WriteLine("---------起头了新线程---------");

    Thread.Sleep(2000);//wait

    Console.WriteLine("---------线程竣事---------");

    }

    //不需要传递参数

    private static void noParmaThread()

    {

    ThreadStart threadStart = new ThreadStart(StartThread);

    var thread = new Thread(threadStart);

    thread.Start();//起头线程

    }

    }

  3. 3

    3 步调2的运行成果,如下图

  4. 4

    4. 含参数多线程。

    static void Main(string[] args)

    {

    int num = 3;

    for ( int i =0; i < num; i++)

    {

    oneParamThread("第" + i.ToString() +"个");

    }

    }

    private static void oneParamThread( string param)

    {

    var thread = new Thread(new ParameterizedThreadStart(StartThread));

    thread.SetApartmentState(ApartmentState.STA);

    thread.IsBackground = true;

    thread.Start(param);

    thread.Join();

    }

    private static void StartThread(Object obj)

    {

    string s = obj as string;

    Console.WriteLine("---------起头了 "+s +" 新线程---------");

    Thread.Sleep(2000);//wait

    Console.WriteLine("---------线程 "+s+" 竣事---------");

    }

  5. 5

    5. 步调4的运行成果如下图所示

  6. 6

    6. 利用专门的线程类。代码如下

    class Program

       {

           static void Main(string[] args)

           {

               int num = 3;

               for ( int i =0; i < num; i++)

               {

                   MyThreadClass mt = new MyThreadClass(i);

                   ThreadStart threadStart = new ThreadStart(mt.StartThread);

                   Thread thread = new Thread(threadStart);

                   thread.Start();

                   //期待线程竣事

               }

           }

       }

       public class MyThreadClass

       {

           public string output { set; get; }

           public int parame { set; get; }

           public MyThreadClass(int p)

           {

               this.parame = p;

           }

           public void StartThread()

           {

               Console.WriteLine("---------起头了 " + parame.ToString() + " 新线程---------");

               Thread.Sleep(2000);//wait

               output = "线程 "+ parame+" 竣事了";

               Console.WriteLine("---------线程 " + parame.ToString() + " 竣事---------");

           }

       }

  7. 7

    7. 步调6的成果如下图

  8. 8

    若是您感觉有效,记得鄙人方点击投票、点赞、存眷、留言,小编会按期送上更多的惊喜哦,您的撑持才是小编继续尽力的动力,么么哒。

来源:百闻(微信/QQ号:9397569),转载请保留出处和链接!


本文链接:https://www.ibaiwen.com/web/238657.html

张子豪

张子豪

TA很懒,啥都没写...

@百闻娱乐 本站部分内容转自互联网,若有侵权等问题请及时与本站联系,我们将在第一时间删除处理。 | 粤ICP备2024343649号 | (地图