C#多线程问题求解答

runerback runerback 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
在一个类里开几个工作线程,并且在类被释放之前(调用Dispose方法)都保持运行。线程方法里面使用while(true)来保持运行,为了节省开销用AutoResetEvent控制。
整个流程是在一个项目里看到的,我把关键部分的代码提出来:

public class ThreadsTest : IDisposable
{
public ThreadsTest()
{
this.threads = new List<Thread>();
this.Initialized = false;
this.Disposing = false;
this.blocker = new AutoResetEvent(false);

int processerCount = Environment.ProcessorCount > 0 ?
Environment.ProcessorCount : 1;
for (int i = 0; i < processerCount; i++)
{
Thread thread = new Thread(this.ThreadFunc);
thread.Name = string.Format("Threads test worker thread {0}", i);
thread.IsBackground = true;
thread.Priority = ThreadPriority.Lowest;
thread.Start();
this.threads.Add(thread);
}
this.Initialized = true;
this.blocker.Set();
}

public bool Initialized { get; private set; }
public bool Disposing { get; private set; }

private List<Thread> threads;
private AutoResetEvent blocker;
public event Action Disposed;

private void ThreadFunc()
{
if (!this.Initialized)
{
this.blocker.WaitOne();
}
while (true)
{
if (this.Disposing)
{
break;
}
Console.WriteLine("{0} running.", Thread.CurrentThread.Name);
this.blocker.WaitOne();
}
if (this.Disposed != null)
{
this.Disposed();
}
}

public void Dispose()
{
this.Disposing = true;
this.blocker.Set();
}
}

本来原来是没有手动释放功能的,我自己加上后,在执行Dispose方法之后,我看了下Thread List里面的线程,只有一个被释放了(Alive为false),其它的还在继续运行。
所以想知道AutoResetEvent 是不是只对一个线程起作用,还有这种情况下如何设计才能“准确”释放掉所有相关的后台工作线程。
...全文

相关推荐

评论 9
收藏 已收藏
分享
返回顶部
runerback
C# 111,128 成员 642,536 内容