我试图准确地了解QueueBackgroundWorkerItem线程启动的任务的状态.我可以访问Task对象并将它们添加到我的TaskModel列表中,并将该列表对象发送到我的View.
我的视图只显示一个任务状态,无论我单击QueueWorkItem链接多少次,并启动一个新任务.我想弄清楚几件事:
我希望有人做过类似的事情并且可以帮助解决这个问题.谢谢!-Jason
编辑:此设置的核心要求是:
控制器:
List<TaskModel> taskModelList = new List<TaskModel>();
public ActionResult QueueWorkItem()
{
Task task;
ViewBag.Message = "State: ";
String printPath = @"C:\Work\QueueBackgroundWorkerItemPractice\QueueBackgroundWorkerItemPractice\WorkerPrintFile" + DateTime.Now.ToLongTimeString().ToString().Replace(":", "_") + ".txt";
System.Web.Hosting.HostingEnvironment.QueueBackgroundWorkItem(cancellationToken =>
{
task = Task.Run(() =>
{
string filePath = printPath;
string text = "File line ";
if (!System.IO.File.Exists(filePath))
{
using (var stream = System.IO.File.Create(filePath)) { }
}
TextWriter tw = new StreamWriter(printPath);
for (int i = 0; i < 400; i++)
{
text = …Run Code Online (Sandbox Code Playgroud) 根据我读过的有关 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 …