2013-03-16 117 views
0

我在寫一個WCF服務,它具有來自多個源的源數據。這些是各種格式的大文件。正確使用代理和多線程

我已經實現了緩存並設置了一個輪詢間隔,以便這些文件保持最新的數據。

我已經構建了一個基本上負責將XDocument對象返回給調用者的管理器類。經理類首先檢查緩存是否存在。如果它不存在 - 它會調用檢索新數據。這裏沒什麼大的。

我想做的事情,以保持響應snappy序列化以前下載的文件,並將該回傳給調用者 - 再次沒有新的......但是......我想盡快產生一個新的線程序列化完成以檢索新數據並覆蓋舊文件。這是我的問題...

不可否認的是一箇中級程序員 - 我遇到過多線程的幾個例子(這裏就是這個問題)...問題是它引入了代表的概念,我真的很掙扎這個。

下面是我的一些代碼:

//this method invokes another object that is responsible for making the 
    //http call, decompressing the file and persisting to the hard drive. 
    private static void downloadFile(string url, string LocationToSave) 
    { 
     using (WeatherFactory wf = new WeatherFactory()) 
     { 
      wf.getWeatherDataSource(url, LocationToSave); 
     } 
    } 

    //A new thread variable 
    private static Thread backgroundDownload; 

    //the delegate...but I am so confused on how to use this... 
    delegate void FileDownloader(string url, string LocationToSave); 

    //The method that should be called in the new thread.... 
    //right now the compiler is complaining that I don't have the arguments from 
    //the delegate (Url and LocationToSave... 
    //the problem is I don't pass URL and LocationToSave here... 
    static void Init(FileDownloader download) 
    { 
     backgroundDownload = new Thread(new ThreadStart(download)); 
     backgroundDownload.Start(); 
    } 

我想實現這個正確的方法......所以有點如何使這項工作教育,將不勝感激。

+0

所以,你有一個緩存,你在後臺更新緩存?這看起來不是什麼大問題,我會給你寫一些代碼。 – theMayer 2013-03-16 18:55:37

+0

許多關於線程的書籍都被編寫了。你不能在這裏要求一個,請訪問你當地的圖書館或書店。 – 2013-03-16 19:00:07

+0

我並不真的在詢問線程。我或多或少地問如何使用線程代表。 – JDBennett 2013-03-16 19:16:46

回答

0

我會用Task Parallel library做到這一點:

//this method invokes another object that is responsible for making the 
//http call, decompressing the file and persisting to the hard drive. 
private static void downloadFile(string url, string LocationToSave) 
{ 
    using (WeatherFactory wf = new WeatherFactory()) 
    { 
     wf.getWeatherDataSource(url, LocationToSave); 
    } 
    //Update cache here? 
} 

private void StartBackgroundDownload() 
{ 
    //Things to consider: 
    // 1. what if we are already downloading, start new anyway? 
    // 2. when/how to update your cache 
    var task = Task.Factory.StartNew(_=>downloadFile(url, LocationToSave)); 
}