如果网页关闭,则完成QueueBackgroundWorkItem

时间:2018-03-14 14:42:54

标签: c# asp.net-mvc iis backgroundworker

根据文献,我已经阅读了有关QueueBackgroundWorkItem的文章,我应该能够在后台完成一项长任务,而不会被IIS打断。

我想知道是否可能,如果我开始一项长期任务并在完成之前关闭我的网站,那么QueueBackgroundWorkItem不应该完成任务吗? (目前不是)

以下是我的电话:

private async Task WriteTextAsync(CancellationToken cancellationToken)
{
    string filePath = printPath;
    string text;
    byte[] encodedText = Encoding.Unicode.GetBytes(text);

    for (int i = 0; i < 200; i++)
    {
        text = "Line " + i + "\r\n";
        encodedText = Encoding.Unicode.GetBytes(text);
        using (FileStream sourceStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None,                    bufferSize: 4096, useAsync: true))
        {
            await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
        };
        Thread.Sleep(200);
    }
}

private void QueueWorkItem()
{
    Func<CancellationToken, Task> workItem = WriteTextAsync;
    HostingEnvironment.QueueBackgroundWorkItem(workItem);
}
编辑:我已经开始工作了。我把它整理了一下。这现在在浏览器关闭后执行,大约3-4分钟,所有内容都写入文件。感谢所有参与其中的人。

private void QueueWorkItem()
{
    HostingEnvironment.QueueBackgroundWorkItem(cancellationToken =>
    {
        string filePath = printPath;
        string text = "File line ";
        TextWriter tw = new StreamWriter(printPath);

        for (int i = 0; i < 400; i++)
        {
            text = "Line " + i;

            tw.WriteLine(text);

            Thread.Sleep(200);
        }

        tw.Close();
    });
}

1 个答案:

答案 0 :(得分:2)

当您使用HostingEnvironment.QueueBackgroundWorkItem时,您必须记住该任务在asp.net工作进程中运行。因此,如果IIS在没有请求20分钟后关闭工作进程(这是默认设置),那么您的任务也会关闭。

如果你的后台任务应该每X次运行一次,那么将它添加到global.asax Application_Start是个好主意。像这样:

在global.asax Application_Start中:

System.Web.Hosting.HostingEnvironment.QueueBackgroundWorkItem(async (t) => { await BackgroundJob.RunAsync(t); });

你的背景课程:

public static class BackgroundJob
{
   public static async Task RunAsync(CancellationToken token)
   {
      ... your code

      await Task.Delay(TimeSpan.FromMinutes(5), token);
   }
}

IIS应用程序池配置

在应用池高级设置中,将空闲超时更改为零,这样当您没有请求一段时间后,后台任务就不会停止运行:

enter image description here