我有一个应用程序,它在后台查询数据,构建一个应用程序查询的本地版本。
我正在使用Task.Run()
我正在使用AutoResetEvent
来指示任务在关闭时终止。
我在Application_Start
开始构建本地数据。
我正在Wait
Application_End
我在Application_Start
private Task SalesDataTask = null;
private AutoResetEvent SalesTerminate = new AutoResetEvent(false);
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
// - removed - AuthConfig.RegisterAuth();
DateTime eleven = DateTime.Now.Date.AddHours(23);
TimeSpan diff = DateTime.Now < eleven ?
eleven - DateTime.Now :
DateTime.Now.AddDays(1).Date.AddHours(23) - eleven;
int hours24 = 24 * 60 * 60 * 1000;
{ // scope variables...
string filename = GetSalesDataPath(DateTime.Now);
if (!File.Exists(filename))
{
// create today's file.
SalesDataTask = Task.Run(async () => { await WriteSalesDataToFile(filename); });
}
else SalesDataTask = Task.Run(() => { return; });
}
System.Threading.Timer timer = new System.Threading.Timer(state =>
{
// create tomorrows file
SalesDataTask.Wait();
string filename = GetSalesDataPath(DateTime.Now.AddDays(1));
SalesDataTask = Task.Run(async () => { await WriteSalesDataToFile(filename); });
}, null, diff.Milliseconds, hours24);
Application["WaitForFile"] = new WaitForFile(this.WaitForFileTasks);
}
Application_End
protected void Application_End()
{
SalesTerminate.Set();
SalesDataTask.Wait();
}
Task
线程
async private Task WriteSalesDataToFile(string path)
{
if (System.IO.File.Exists(path))
{
throw new System.IO.IOException("File already exists");
}
var dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
using (FileStream stream = new FileStream(path, FileMode.CreateNew))
{
using (XmlWriter writer = XmlWriter.Create(stream))
{
writer.WriteStartElement("SalesData");
await FMEext.QuerySalesData("dom", (x) =>
{
// callback to handle a block of
// data that is fetched from the REST service
x.Elements().ToList().ForEach(e =>
{
writer.WriteRaw(e.ToString());
});
// return true to continue processing
// return false to terminate processing.
return !SalesTerminate.WaitOne(10, true);
}).ConfigureAwait(false);
writer.WriteEndElement();
writer.Flush();
}
}
}
我遇到的问题是应用程序在我的Task
主题有机会完成“终止”之前终止。