【发布时间】:2012-02-29 04:46:53
【问题描述】:
我有以下代码来帮助我理解多线程,它的目的是创建 3 个带有调试代码的后台工作线程来显示线程使用/可用性。 现在代码看起来不错,但有时我会得到意想不到的结果。
调用代码:
static void Main(string[] args)
{
ThreadPool.CreatWorkBetter();
Console.ReadLine();
}
实现代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using t = System.Threading;
namespace CSharpConcepts
{
public static class ThreadPool
{
private static t.ManualResetEvent[] resetEvent;
public static void CreatWorkBetter()
{
Console.WriteLine("Start");
ListAvailableThreads();
resetEvent = new t.ManualResetEvent[3];
resetEvent[0] = new t.ManualResetEvent(false);
resetEvent[1] = new t.ManualResetEvent(false);
resetEvent[2] = new t.ManualResetEvent(false);
t.ThreadPool.QueueUserWorkItem(
new t.WaitCallback(delegate(object state)
{
PooledFunc("Stage 1", resetEvent[0]);
}));
t.ThreadPool.QueueUserWorkItem(
new t.WaitCallback(delegate(object state)
{
PooledFunc("Stage 2", resetEvent[1]);
}));
t.ThreadPool.QueueUserWorkItem(
new t.WaitCallback(delegate(object state)
{
PooledFunc("Stage 3", resetEvent[2]);
}));
t.WaitHandle.WaitAll(resetEvent);
Console.WriteLine("Finished");
ListAvailableThreads();
}
static void PooledFunc(object state, t.ManualResetEvent e)
{
Console.WriteLine("Processing request '{0}'", (string)state);
// Simulation of processing time
t.Thread.Sleep(2000);
Console.WriteLine("Request processed");
ListAvailableThreads();
e.Set();
}
public static void ListAvailableThreads()
{
int avlThreads, avlToAsynThreads;
t.ThreadPool.GetAvailableThreads(out avlThreads, out avlToAsynThreads);
string message = string.Format("Processed request: {3}, From ThreadPool :{0} ,Thread Id :{1},Free Threads :{2}",t.Thread.CurrentThread.IsThreadPoolThread,t.Thread.CurrentThread.ManagedThreadId,avlThreads,t.Thread.CurrentThread.ThreadState);
Console.WriteLine(message);
}
}
}
我所期望的结果是明智的,而且大部分时间我都得到了它(显示的关键线是空闲线程回到 1023 是我真正想看到的):
开始处理的请求:正在运行,来自 ThreadPool :False ,线程 ID :1,空闲线程:1023 处理请求“阶段 1”处理请求 'Stage 2' 处理请求 'Stage 3' 请求已处理 已处理 请求:背景,来自线程池:True,线程 ID:4,空闲线程 :1020 请求已处理处理的请求:后台,来自 ThreadPool :真,线程 ID:3,空闲线程:1021 请求已处理已处理 请求:背景,来自线程池:True,线程 ID:5,空闲线程 :1022 已完成处理的请求:正在运行,来自 ThreadPool :False ,Thread Id :1,Free Threads :1023
但是,我有时会看到显示 1022 的空闲线程,我希望它是 1023,因为 3 个线程已经完成了工作,所以它们应该已经返回到线程池:
开始处理的请求:正在运行,来自 ThreadPool :False ,线程 ID :1,空闲线程:1023 处理请求“阶段 1”处理请求 'Stage 2' 处理请求 'Stage 3' 请求已处理 已处理 请求:背景,来自线程池:True,线程 ID:3,空闲线程 :1020 请求已处理处理的请求:后台,来自 ThreadPool :真,线程 ID:4,空闲线程:1020 请求已处理已处理 请求:背景,来自线程池:True,线程 ID:5,空闲线程 :1022 已完成处理的请求:正在运行,来自线程池:False,线程 ID:1,空闲线程:1022
有什么想法吗?
【问题讨论】:
-
您确定这是您的工作线程之一不是免费的吗?会不会是垃圾收集器?
标签: c# .net multithreading