发出信号后,处置自身
我们假设我们有一个类 myqueue 定义为以下:
public class MyQueue
{
private bool _stop;
private readonly AutoResetEvent _onQueued = new AutoResetEvent(false);
private readonly ConcurrentQueue<int> _queue = new ConcurrentQueue<int>();
public MyQueue()
{
var thread = new Thread(ManageQueue)
{
IsBackground = true
};
thread.Start();
}
public void EnqueueInt(int num)
{
_queue.Enqueue(num);
_onQueued.Set();
}
public void Stop()
{
_stop = true;
_onQueued.Set();
}
private void ManageQueue()
{
while (!_stop)
{
onQueued.WaitOne();
int tempNum;
while(!_stop && _queue.TryDequeue(out tempNum))
{
// Do something with the int
}
}
}
}
因此,我们有一个方法 enqueInt
用于在数据结构内排队项目和 thread> thread
该周期性检查队列是否有要处理的项目。信号 _onqueed
用于在插入新项目或启动关闭操作时发出信号。我的问题是:Myqueue具有一次性对象( autoresetevent ),必须在不再需要队列时处置,但是,处置它的最佳方法是什么?
呼叫 distose
在关闭()
操作之后可能非常危险,因为其中 set()
invocation,我没有Garantee认为线程已终止其周期。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
相反,或重新启动轮子,您可以使用 system.collections.generic.queue&lt; t&gt;
另外,如果您要管理队列的寿命,我将使用服务,因此,当服务(queue服务)被处置时,那么您可以处置它;这是有关如何创建队列服务的Microsoft指南:
Instead or re-inventing the wheel, you can use System.Collections.Generic.Queue<T>
Also, if you want to manage the lifetime of your queue, I would use a service, so when the service (queue service) is disposed, then you can dispose of it; here is the Microsoft guide on how to create a queue service: https://learn.microsoft.com/en-us/dotnet/core/extensions/queue-service