如何将数据从Threadpool输出到ConcurrentQueue(C#)?

时间:2018-06-25 20:33:47

标签: c# multithreading concurrency threadpool concurrent-queue

我为我的公司编写了一个应用程序,该应用程序实际上是将文本或CSV文件中的记录以100条记录的数组形式发送到Web服务,然后向该服务返回响应(也以100条记录的数组形式)并将它们写到另一个文件。当前,它是单线程的(使用Windows Pro Forms中的Backgroundworker进行顺序处理),但是我正在寻求利用线程池和并发队列对其进行多线程处理。

#region NonDataCollectionService
if (!userService.needsAllRecords)
{
    ConcurrentQueue<Record[]> outputQueue = new ConcurrentQueue<Record[]>();
    while ((!inputFile.checkForEnd()) && (!backgroundWorker1.CancellationPending)) 
    {
        //Get array of (typically) 100 records from input file
        Record[] serviceInputRecord = inputFile.getRecords(userService.maxRecsPerRequest);
        //Queue array to be processed by threadpool, send in output concurrentqueue to be filled by threads
        ThreadPool.QueueUserWorkItem(new WaitCallback(sendToService), new object[]{serviceInputRecord, outputQueue});
    }
}
#endregion



void sendToService(Object stateInfo)
{
    //The following block is in progress, I basically need to create copies of my class that calls the service for each thread
    IWS threadService = Activator.CreateInstance(userService.GetType()) as IWS;
    threadService.errorStatus = userService.errorStatus;
    threadService.inputColumns = userService.inputColumns;
    threadService.outputColumns = userService.outputColumns;
    threadService.serviceOptions = userService.serviceOptions;
    threadService.userLicense = userService.userLicense;

    object[] objectArray = stateInfo as object[];

    //Send input records to service
    threadService.sendToService((Record[])objectArray[0]);
    //The line below returns correctly
    Record[] test123 = threadService.outputRecords;
    ConcurrentQueue<Record[]> threadQueue = objectArray[1] as ConcurrentQueue<Record[]>;
    //threadQueue has records here
    threadQueue.Enqueue(test123);
}

但是,当我在最上面的块中检查“ outputQueue”时,它是空的,即使threadQueue已将记录排队。这是因为我是通过值传递而不是通过引用传递?如果是这样,我该如何使用Threadpool.QueueUserWorkItem进行语法处理?

0 个答案:

没有答案