Jas*_*ger 1 c# iis asp.net-mvc 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);
}
Run Code Online (Sandbox Code Playgroud)
编辑:我已经得到了这个工作。我修剪了它。现在在浏览器关闭后执行,大约 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();
});
}
Run Code Online (Sandbox Code Playgroud)
当您使用 时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); });
Run Code Online (Sandbox Code Playgroud)
你的背景课:
public static class BackgroundJob
{
public static async Task RunAsync(CancellationToken token)
{
... your code
await Task.Delay(TimeSpan.FromMinutes(5), token);
}
}
Run Code Online (Sandbox Code Playgroud)
IIS应用程序池配置
在应用程序池高级设置中,将空闲超时更改为零,这样您的后台任务不会在一段时间没有请求时停止运行:
| 归档时间: |
|
| 查看次数: |
2603 次 |
| 最近记录: |