Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用.Net c#中的任务创建单线程队列?_C#_Multithreading_Task Queue - Fatal编程技术网

如何使用.Net c#中的任务创建单线程队列?

如何使用.Net c#中的任务创建单线程队列?,c#,multithreading,task-queue,C#,Multithreading,Task Queue,我有一个监控数据库表更改的服务。我目前正在使用静态backgroundworker对数据库的调用进行排队。为了限制数据库选择调用,每次运行bgw时我都会转储队列。如果需要,队列实际上只是告诉bgw在完成时再次运行 有没有更好的方法来完成这项任务 static Queue<int> _Queue = new Queue<int>(); static BackgroundWorker _bgw; public RunTask() { If (_bgw == null

我有一个监控数据库表更改的服务。我目前正在使用静态backgroundworker对数据库的调用进行排队。为了限制数据库选择调用,每次运行bgw时我都会转储队列。如果需要,队列实际上只是告诉bgw在完成时再次运行

有没有更好的方法来完成这项任务

static Queue<int> _Queue = new Queue<int>();
static BackgroundWorker _bgw;

public RunTask()
{
    If (_bgw == null)
    {
        _bgw = new BackgroundWorker();

        _bgw.DoWork += (s,e) =>
            { //work}

        _bgw.RunWorkerCompleted += (s,e) =>
        { 
            if (_Queue.Any())
            {
               _Queue.Clear();
               _bgw.RunWorkerAsync();
            }
        }

    }

    _Queue.Enqueue(1);

    if (!_bgw.IsBusy())
    {
       _Queue.Clear();
        _bgw.RunWorkerAsync();
    }
}
静态队列_Queue=new Queue();
静态后台工作人员_bgw;
公共运行任务()
{
如果(_bgw==null)
{
_bgw=新的BackgroundWorker();
_bgw.DoWork+=(s,e)=>
{//work}
_bgw.RunWorkerCompleted+=(s,e)=>
{ 
if(_Queue.Any())
{
_Queue.Clear();
_bgw.RunWorkerAsync();
}
}
}
_排队。排队(1);
如果(!\u bgw.IsBusy())
{
_Queue.Clear();
_bgw.RunWorkerAsync();
}
}

我建议使用
BlockingCollection
而不是队列。谢谢我发现的一些文档还建议使用大小为1的信号量lim。您能给我一个简短的代码示例,说明我上面的代码如何与BlockingCollection和Task一起工作吗?提前谢谢。