如何使ASP.NET应用程序等待任务完成

时间:2016-03-03 19:29:44

标签: c# asp.net-mvc multithreading

我有一个应用程序,它在后台查询数据,构建一个应用程序查询的本地版本。

我正在使用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主题有机会完成“终止”之前终止。

0 个答案:

没有答案