温馨提示×

c# threadstart如何使用匿名函数

c#
小樊
83
2024-06-24 10:08:35
栏目: 编程语言

使用匿名函数启动线程可以通过以下步骤实现:

  1. 创建一个新的ThreadStart委托实例,该委托将指向一个匿名函数。
  2. 在匿名函数中编写要在新线程中执行的代码。
  3. 使用Thread类的构造函数创建一个新的线程,并将ThreadStart委托作为参数传递。
  4. 调用新线程的Start方法启动线程。

下面是一个示例代码,展示了如何使用匿名函数启动线程:

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        // 创建一个新线程,并在匿名函数中编写要执行的代码
        Thread thread = new Thread(new ThreadStart(() =>
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("Thread is running... {0}", i);
                Thread.Sleep(1000);
            }
        }));

        // 启动线程
        thread.Start();

        Console.WriteLine("Main thread is running...");

        Console.ReadLine();
    }
}

在这个示例中,我们创建了一个新的线程,并在匿名函数中编写了一个简单的循环,每隔1秒打印一次消息。然后通过调用Start方法启动线程。同时主线程也在不断打印消息,展示了多线程的同时运行。您可以根据自己的需求在匿名函数中编写相应的代码。

0