ManualResetEvent verseus Async / Await

时间:2014-07-21 03:19:10

标签: c# multithreading

我有以下类来排队/出队对象(等待响应)。

public class PendingQueue<TValue> : Queue<TValue>, IDisposable
{
    private ManualResetEvent QueueDone = new ManualResetEvent(false);

    public PendingQueue() : base() { }

    public new void Enqueue(TValue item)
    {
        base.Enqueue(item);

        this.QueueDone.Set();
    }

    public new TValue Dequeue()
    {
        this.QueueDone.WaitOne();

        TValue result = base.Dequeue();

        this.QueueDone.Reset();

        return result;
    }

    public void Dispose()
    {
        this.QueueDone.Dispose();
    }
}

基本上,当我想“暂停”我的脚本并等待响应时,我只使用以下代码:

   public bool SomeMethod()
{
    this.PendingQueue = new PendingQueue<bool>();

    return this.PendingQueue.Dequeue();
}

然后,我只是使用PendingQueue将一个布尔对象排入队列,然后返回该对象。

现在,我的问题是它使整个线程卡住了。我将它用于脚本(使用C#中的CodeDomProvider编译)。我以前使用TaskCompletionSource然后使用await / async,但我想使用这个类因为我不喜欢任务。

如何使像async / await一样卡在整个线程中?我不想在不同的线程上运行脚本(当我执行它们时)。

感谢。

1 个答案:

答案 0 :(得分:1)

首先,如果你以任何其他方式使用PendingQueue,那么ManualResetEvent会非常糟糕。比如说,如果你有两个项目在排队之前排队。

  

现在,我的问题是它使整个线程卡住了。

这是async和其他传统线程同步原语的重点。

  

如何让它不像async / await那样陷入整个线程?

您使用await / Task和{{1}}。这是他们存在的全部观点。