0

我正在编写一个具有来自多个源的源数据的 WCF 服务。这些是各种格式的大文件。

我已经实现了缓存并设置了轮询间隔,以便这些文件保持最新数据。

我构建了一个管理器类,它基本上负责将 XDocument 对象返回给调用者。管理器类首先检查缓存是否存在。如果它不存在 - 它会调用以检索新数据。这里没什么大不了的。

为了保持响应快速,我想做的是序列化先前下载的文件并将其传递回调用者 - 再次没有什么新东西......但是......我想在序列化完成后立即生成一个新线程检索新数据并覆盖旧文件。这是我的问题...

诚然,一名中级程序员 - 我遇到了一些关于多线程的示例(在这里)......问题是它引入了委托的概念,我真的很挣扎。

这是我的一些代码:

//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();
    }

我想以正确的方式实现这一点......所以对如何进行这项工作进行一些教育将不胜感激。

4

1 回答 1

1

我会使用Task Parallel 库来做到这一点:

//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));
}
于 2013-03-16T18:59:27.393 回答