我需要關於如何最好地設計一組類用於管理多線程C#應用程序,我發展一些幫助。 我已經成功創建了一個ThreadContainer類來啓動一系列線程。 主題從特定網站下載財務數據。 對於每個通過的網站,他們將打開相同的基本網址,但使用不同的符號。 因此,#結果等於每個網站傳遞的符號數量。 然後,根據該請求的線程結果以不同的方式處理的網站上... 這裏是簡化ThreadContainer代碼:一流的設計 - 如何管理多個線程響應
public class ThreadContainer
{
private int ConcurrentThreads;
private string Website;
public string URL;
private Queue SymQueue;
//Constructor
public ThreadContainer(string website, Queue symQueue)
{
Website = website;
SymQueue = symQueue;
}
//Start
public void start(int concurrent)
{
ConcurrentThreads = concurrent;
//Start the Concurrent Threads
for (int ThreadNum = 1; ThreadNum <= ConcurrentThreads; ThreadNum++)
{
//Get a symbol from the queue
Sym = SymQueue.Dequeue().ToString();
//Build the URL
URL = string.Format(Constants.URL(Website), Sym);
//Create a new Asynch thread
AsynchThread j = new AsynchThread(ThreadNum);
//Start the AsyncThread class with the BackgoundWorker
j.Start(Sym, URL);
}
}
//Method called when the Backgroundworker thread has terminated
private void AsynchThread1_JobCompleted(object sender, EventArgs e)
{
// Get the AsynchThread object
AsynchThread j = (AsynchThread)sender;
//Get the symbol name
String Sym = j.Sym;
//Get the result with the Webpage content
RunWorkerCompletedEventArgs re = e as RunWorkerCompletedEventArgs;
String result = re.Result.ToString();
/* HERE EACH THREAD RETURNS THE WEBSITE CONTENT.
* DEPENDING ON THE WEBSITE THAT WAS REQUESTED SEVERAL ACTIONS MAY BE EXECUTED.
*/
switch(website)
{
case "WebsiteA":
// With WebsiteA I would like to :
// 1. extract the symbol data
// 2. return the result for this symbol to the calling class.
case "WebsiteB":
// With WebsiteB I would like to:
// 1. extract the symbol data (Webpage design is different from WebsiteA)
// 2. store each symbol data in a database table
case "WebsiteC":
// With WebsiteB I would like to:
// 1. extract the symbol data (Webpage design is different from WebsiteA and WebsiteB)
// 2. put the results in a queue
case ...
default:
return "";
}
// Reuse the thread that has just completed
//If there are items left in the queue...
if (SymQueue.Count > 0)
//...get the new Sym value...
NewSym = SymQueue.Dequeue().ToString();
//If NewSym is valid ...
if (!String.IsNullOrEmpty(NewSym))
{
//...build the URL...
String NewURL = string.Format(Constants.URL(Website), NewSym);
//...then restart the thread with the new parameters
j.Start(NewSym, NewURL);
}
}
}
我想知道什麼是設計的最好方式AsynchThread1_JobCompleted 方法。 當每個線程終止,應執行以下任務,這種方法被稱爲:
- 得到的網頁內容
- 從網頁中提取數據
- 將數據發送給調用者或保存數據到數據庫或將數據插入到隊列中。
- 檢查隊列是否仍有項目,並使用新的URL重新啓動線程,以便打開新的網頁。
我該如何設計方法,以便每次需要添加新網站時都不必修改代碼? 另外,我應該使用相同的AsynchThread,下載頁面提取數據,保存到數據庫等...或者更好的另一個線程呢? 我想有以下一種單一職責原則的ThreadContainer類...
感謝
您定位的是什麼版本的.NET框架? – 2012-03-01 16:04:29
.Net版本4. – Forna 2012-03-01 16:06:09
也許只是將結果排入隊列