创建线程并等待C#

时间:2020-05-19 19:54:04

标签: c#

我有一段代码可以在while循环中生成客户:

Queue queue = new Queue();
while (continueGenerating)
    {
        Thread.Sleep(3000);
        Customer customer = new Customer();
        queue.DoSmth(customer);
    }

和一个班级队列:

public class Queue
    {
        public void DoSmth(Customer customer) 
        {
            Console.WriteLine("New customer");
        }
    }

问题是这样的:我需要在程序的前面创建一个线程,并等待直到生成新客户为止。仅在生成客户之后,函数queue.DoSmth(customer)才被调用。

我知道可以使用事件和事件处理程序解决它,但是我不知道它应如何与线程一起使用。 预先谢谢你!

1 个答案:

答案 0 :(得分:0)

这是我在类似情况下用于安排在单个后台线程上进行操作的情况的简化版本

class BackgroundThread
{
    private readonly _queue = new BlockingCollection();
    private Thread _backgroundThread;

    public BackgroundThread() : IDisposable
    {
        _backgroundThread = new Thread(run)
        {
            IsBackground = true
        };
        _thread.SetApartmentState(ApartmentState.STA);
        _thread.Start();
    }

    public Task Enqueue(Action action)
    {
        var task = new Task(action);
        _queue.Add(task);
        return task;
    }

    public void Dispose()
    {
        _queue.CompleteAdding();
        _thread.Join();
    }

    private void run()
    {
        foreach (var task in _queue.GetConsumingEnumerable())
        {
            task.RunSynchonously();
        }
    }
}

因此,在您的情况下,您将使用类似的方式

using (var bt = new BackgroundThread)
{
    while (continueGenerating)
    {
        Thread.Sleep(3000);
        Customer customer = new Customer();
        bt.Enqueue(() => { queue.DoSmth(customer); });
    }
}

在这种情况下,我没有使用Enqueue返回的任务,但是您可以使用该任务来Waitawait任务,或者捕获/处理异常或取消。

相关问题