小编Jas*_*ger的帖子

如何存储任务的活动状态,并维护这些任务的列表的永久性

我试图准确地了解QueueBackgroundWorkerItem线程启动的任务的状态.我可以访问Task对象并将它们添加到我的TaskModel列表中,并将该列表对象发送到我的View.

我的视图只显示一个任务状态,无论我单击QueueWorkItem链接多少次,并启动一个新任务.我想弄清楚几件事:

  • 在MVC中,如何保存我生成的任务数量的实时列表?我假设将模型发送到视图中,我会保证一些永久性.
  • 一旦我能做到这一点,我想我可以将Task对象存储在我的列表中.但是,即使在下面的这个例子中,我似乎仍然无法知道在任何给定时间任务的状态是什么(似乎我只能知道它在添加到我的列表时是什么) .

我希望有人做过类似的事情并且可以帮助解决这个问题.谢谢!-Jason

编辑:此设置的核心要求是:

  • 即使浏览器关闭,我也需要使用QueueBackgroundWorkerItem来运行一个很长的工作
  • 我选择嵌入一个任务,这样我就可以了解每个工作的持续状态.我理解,对于QBWI,运行任务会有点过分.但我无法找到任何其他方式来了解QBWI的状态.

控制器:

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)

c# asp.net iis session-variables task

7
推荐指数
1
解决办法
198
查看次数

如果网页关闭,则让 QueueBackgroundWorkItem 完成

根据我读过的有关 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 …

c# iis asp.net-mvc backgroundworker

1
推荐指数
1
解决办法
2603
查看次数