为线程同步排队更改此代码是否简单
本文关键字:代码 是否 简单 线程 同步 排队 | 更新日期: 2023-09-27 18:00:44
我正在尝试运行文章Thread Synchronized Queing 中的代码
但是得到编译错误:
找不到类型或命名空间名称"T"(是否缺少使用指令还是程序集引用?)
我的猜测是,它使用的是泛型,虽然我没有太多经验,但更改应该很微不足道。
我应该如何更改此代码?
我希望有一个非常简单的改变,否则就忘了
那篇文章的代码:
using System;
using System.Collections;
using System.Collections.Generic;//per comment by @jam40jeff to answer
using System.Threading;
namespace QueueExample
{
public class SyncQueue// per answer --> public class SyncQueue<T>
{
private WaitHandle[] handles = {
new AutoResetEvent(false),
new ManualResetEvent(false),
};
private Queue _q = new Queue();
////per comment by @jam40jeff to answer, the above line should be changed to
// private Queue<T> _q = new Queue<T>();
public int Count
{
get
{
lock (_q)
{
return _q.Count;
}
}
}
public T Peek() //******error************************
{
lock (_q)
{
if (_q.Count > 0)
return _q.Peek();
}
return default(T);//******error************************
}
public void Enqueue(T element) //******error************************
{
lock (_q)
{
_q.Enqueue(element);
((AutoResetEvent)handles[0]).Set();
}
}
public T Dequeue(int timeout_milliseconds)//******error************************
{
T element;//******error************************
try
{
while (true)
{
if (WaitHandle.WaitAny(handles, timeout_milliseconds, true) == 0)
{
lock (_q)
{
if (_q.Count > 0)
{
element = _q.Dequeue();
if (_q.Count > 0)
((AutoResetEvent)handles[0]).Set();
return element;
}
}
}
else
{
return default(T);//******error************************
}
}
}
catch (Exception e)
{
return default(T);//******error************************
}
}
public T Dequeue() //******error************************
{
return Dequeue(-1);
}
public void Interrupt()
{
((ManualResetEvent)handles[1]).Set();
}
public void Uninterrupt()
{
// for completeness, lets the queue be used again
((ManualResetEvent)handles[1]).Reset();
}
}}
更新:
更改为后
public class SyncQueue<T>
根据答案,也有必要从
return _q.Peek();
至
return (T)_q.Peek();
和
element = _q.Dequeue();
至
element = (T)_q.Dequeue();
更新2:
根据@jam40jeff对答案的评论:
- 将
_q
更改为Queue<T>
类型。然后需要using语句,但不需要强制转换为t
我的更新以上是糟糕的
也许是作者的错误,类SyncQueue
应该是泛型的:
public class SyncQueue<T>
要使用泛型,还需要添加一个using
:
using System.Collections.Generic;
那么上面的代码应该没问题。