簡體   English   中英

在.NET中並發線程之間傳遞數據的最佳方法是什么?

[英]What's the best way to pass data between concurrent threads in .NET?

我有兩個線程,一個需要輪詢一堆獨立的靜態資源來尋找更新。 另一個需要獲取數據並將其存儲在數據庫中。 線程1如何告訴線程2有什么要處理的?

如果數據片段是獨立的,則將數據片段視為要由線程池處理的工作項。 使用線程池和QueueUserWorkItem將數據發布到線程。 您應該使用對稱線程池來獲得更好的可伸縮性,並限制生產者和消費者之間必須發生的同步量。

例如(來自MSDN ):

    TaskInfo ti = new TaskInfo("This report displays the number {0}.", 42);

    // Queue the task and data.
    if (ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti)) {    
        Console.WriteLine("Main thread does some work, then sleeps.");

        // If you comment out the Sleep, the main thread exits before
        // the ThreadPool task has a chance to run.  ThreadPool uses 
        // background threads, which do not keep the application 
        // running.  (This is a simple example of a race condition.)
        Thread.Sleep(1000);

        Console.WriteLine("Main thread exits.");
    }
    else {
        Console.WriteLine("Unable to queue ThreadPool request."); 
    }


// The thread procedure performs the independent task, in this case
// formatting and printing a very simple report.
//
static void ThreadProc(Object stateInfo) {
    TaskInfo ti = (TaskInfo) stateInfo;
    Console.WriteLine(ti.Boilerplate, ti.Value); 
}

我在工作項的隊列上使用Monitor.Wait / Pulse。

“DB中的存儲”線程是否總是需要運行? 似乎最好的選擇(如果可能的話)是讓輪詢線程旋轉另一個線程來進行保存。 根據創建的線程數,可能是第一個輪詢線程使用ThreadPool.QueueUserWorkItem()可能是更有效的路由。

為了提高效率,在保存到數據庫時,我會在數據庫上使用異步I / O而不是同步方法。

任何時候你都可以遠離兩個線程之間的直接通信,你應該。 必須將一些同步原語放在一起,你的代碼將不會那么容易調試,並且可能會引入一些非常微妙的競爭條件,導致“一百萬次執行”類型的錯誤(找到/修復它們很有趣)。

如果第二個線程總是需要執行,請告訴我們為什么有更多信息,我們可以回過頭來獲得更深入的答案。

祝好運!

我個人會有線程1引發線程2可以響應的事件。 線程可以通過控制進程連接到適當的事件,該控制進程啟動兩個線程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM