[.NET4.5.2] 背景工作另一選擇QueueBackgroundWorkItem

目前在Web上若要支援背景工作 例:圖片轉檔、資料轉入等離線工作,有幾種選擇,如:Azure WebJobsHangfire或進階點使用Azure Worker Role等。除了Hangfire(第三方套件)以外,其他2者需執行在Azure的環境上。而目前在.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

這個網誌中的熱門文章

IIS 設定只允許特定IP進入