我正在编写一个包含来自多个源的源数据的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 :(得分:1)
我会使用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));
}