2013-03-16 38 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)); 
}