queueuserworkitem

C#中queueuserworkitem怎么使用

小亿
138
2023-08-02 23:26:34
栏目: 编程语言

在C#中,可以使用QueueUserWorkItem方法来将方法或委托添加到线程池队列中进行异步执行。下面是使用QueueUserWorkItem方法的示例代码:

using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
// 将方法添加到线程池队列中异步执行
ThreadPool.QueueUserWorkItem(DoWork, "Hello, World!");
// 主线程继续执行其他操作
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Main thread doing other work.");
Thread.Sleep(1000);
}
Console.ReadLine();
}
static void DoWork(object state)
{
// 从参数中获取要执行的工作
string message = (string)state;
// 执行工作
Console.WriteLine("Doing work: " + message);
Thread.Sleep(3000);
Console.WriteLine("Work completed: " + message);
}
}

在上面的示例中,我们使用QueueUserWorkItem方法将DoWork方法添加到线程池队列中异步执行。然后,主线程继续执行其他操作。DoWork方法会在后台线程中执行,并输出一些消息。最后,主线程等待用户按下Enter键以结束程序。

请注意,尽管QueueUserWorkItem方法非常方便,但在新的代码中更推荐使用Task类或async/await模式来进行异步编程。

0
看了该问题的人还看了