[.NET4.5.2] 背景工作另一選擇QueueBackgroundWorkItem
.NET 4.5.2內建的QueueBackgroundWorkItem
此功能與ThreadPool.QueueUserWorkItem一樣都是記憶體的序列,但不同的是它支援非同步await/async功能以及會自動保持與追蹤有多少個未完成的工作,並且在應用程式被關閉時(例:更新程式、IIS回收等)會試著延遲90秒直到所有工作完成,當然超過90秒後未完成的工作就會遺失。若你的背景工作是與交易較無關的功能,如發信通知,建議可以使用此API。 protected void Button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 100; i++)
            {
                string root = Server.MapPath("~/Log");
                HostingEnvironment.QueueBackgroundWorkItem(ct => WriteFileLog(root, "Hello world!"));
            }
        }
        private async Task WriteFileLog(string root, string message)
        {
            FileStream file = new FileStream(root + "\\" + Guid.NewGuid().ToString("n") + ".txt", FileMode.Create);
            StreamWriter s = new StreamWriter(file);
            await s.WriteAsync(message);
            s.Dispose();
        }
參考來源
http://www.hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx
