租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

C#中queueuserworkitem如何使用

发布时间:2023-08-03 08:29:16

C#中queueuserworkitem如何使用

在C#中,可使用QueueUserWorkItem方法来将方法或拜托添加到线程池队列中进行异步履行。下面是使用QueueUserWorkItem方法的示例代码:
```csharp
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模式来进行异步编程。