C# 为线程同步排队更改此代码是否简单?
我正在尝试运行文章中的代码 但获取编译错误: 找不到类型或命名空间名称“T”(是否缺少 使用指令或程序集引用?) 我的猜测是,它正在使用泛型,虽然我对它没有太多经验,但变化应该很小。C# 为线程同步排队更改此代码是否简单?,c#,multithreading,generics,collections,synchronization,C#,Multithreading,Generics,Collections,Synchronization,我正在尝试运行文章中的代码 但获取编译错误: 找不到类型或命名空间名称“T”(是否缺少 使用指令或程序集引用?) 我的猜测是,它正在使用泛型,虽然我对它没有太多经验,但变化应该很小。 我应该如何更改此代码 我希望能有一个非常简单的改变,否则就忘了它吧 该条中的代码: using System; using System.Collections; using System.Collections.Generic;//per comment by @jam40jeff to answer usin
我应该如何更改此代码 我希望能有一个非常简单的改变,否则就忘了它吧 该条中的代码:
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();
}
到
来自
element = _q.Dequeue();
到
更新2:根据@jam40jeff对答案的评论:
- 将
更改为\u q
类型。然后您将需要using语句,但不需要将强制转换为tQueue
我上面的更新不好可能是作者的错误,类
SyncQueue
应该是通用的:
public class SyncQueue<T>
那么上面的代码应该可以了。我希望我正确地纠正了其他错误,请参阅我的更新?另外,
使用System.Collections.Generic代码>无需(使用)更改为队列类型
。然后需要using语句,但不需要对t
进行强制转换。
return (T)_q.Peek();
element = _q.Dequeue();
element = (T)_q.Dequeue();
public class SyncQueue<T>
using System.Collections.Generic;