gpt4 book ai didi

multithreading - ThreadPool.QueueUserWorkItem和异步编程

转载 作者:行者123 更新时间:2023-12-03 13:16:24 28 4
gpt4 key购买 nike

我在下面编写了一个示例程序。

class Program
{
static int x = 2;

static void Main(string[] args)
{
Console.WriteLine("Thread ID {0} and Main Called!", Thread.CurrentThread.ManagedThreadId);

ThreadPool.QueueUserWorkItem(Count, args);
ThreadPool.QueueUserWorkItem(Count2, args);

Console.WriteLine("Thread ID {0} and Main Done!", Thread.CurrentThread.ManagedThreadId);
Console.ReadLine();
}
static void Count(object args)
{
for (int i = 0; i < 10; i++)
{
x = x + 2;
Console.WriteLine("Thread ID {0} AND Count 1: " + x, Thread.CurrentThread.ManagedThreadId);
}
}
static void Count2(object args)
{
for (int i = 0; i < 10; i++)
{
x = x + 2;
Console.WriteLine("Thread ID {0} AND Count 2: " + x, Thread.CurrentThread.ManagedThreadId);
}
}
}

当使用ThreadPool.QueueUserWorkItem调用Count方法时,我注意到Main在Count方法完成之前已经完成,并且Count2方法与Count方法纠缠在一起。

无论如何,Main(和Count2)是否可以等待Count方法完成?我不想使用锁或Thread.Sleep(因为我不知道Count操作将花费多长时间)。我读过某个地方的异步调用或WAIT用于这种情况。

有任何想法吗?

最佳答案

我认为AutoResetEvent是您所追求的

**编辑: **
这是修改后的代码(未经测试)。在此示例中,我使用了AutoResetEvent而不是Manual

class Program
{
static int x = 2;
// Define an array with two AutoResetEvent WaitHandles.
static WaitHandle[] waitHandles = new WaitHandle[]
{
new AutoResetEvent(false),
new AutoResetEvent(false)
};



static void Main(string[] args)
{
Console.WriteLine("Thread ID {0} and Main Called!", Thread.CurrentThread.ManagedThreadId);

ThreadPool.QueueUserWorkItem(new WaitCallback(Count), waitHandles[0]);
ThreadPool.QueueUserWorkItem(new WaitCallback(Count2), waitHandles[1]);
WaitHandle.WaitAll(waitHandles);


Console.WriteLine("Thread ID {0} and Main Done!", Thread.CurrentThread.ManagedThreadId);
Console.ReadLine();
}
static void Count(object args)
{
AutoResetEvent are = (AutoResetEvent)args;

for (int i = 0; i < 10; i++)
{
x = x + 2;
Console.WriteLine("Thread ID {0} AND Count 1: " + x, Thread.CurrentThread.ManagedThreadId);
}
are.Set();

}
static void Count2(object args)
{
AutoResetEvent are = (AutoResetEvent)args;

for (int i = 0; i < 10; i++)
{
x = x + 2;
Console.WriteLine("Thread ID {0} AND Count 2: " + x, Thread.CurrentThread.ManagedThreadId);
}
are.Set();
}
}

关于multithreading - ThreadPool.QueueUserWorkItem和异步编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3732577/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com