繁体   English   中英

如何在MVC控制器中检测发送完成

[英]How detect send completed in MVC controller

下面的代码用于在Linux和Windows中创建ASP.NET MVC2应用程序的备份。 完成后,应将条目写入日志文件。 这段代码在进程Exit事件中将其写入。

退出事件写入为时过早:数据可能未发送到客户端。 如果所有数据都已发送,如何写入日志事件? 流没有Closed事件。

public class BackupController : ControllerBase 
    { 
        [AcceptVerbs(HttpVerbs.Get)] 
        public FileStreamResult Backup() 
        { 
            var process = new Process(); 
            process.StartInfo.FileName = "c:\\Program Files\\PostgreSql\\9.1\\bin\\pg_dump.exe"; 
            process.StartInfo.UseShellExecute = false; 
            process.StartInfo.RedirectStandardOutput = true; 
            process.EnableRaisingEvents = true; 
            process.Exited += (sender, e) => 
            { 
                TempData["ExitCode"] = process.ExitCode; 
                // todo: how to write this if all data is sent: 
                Writelog( "Backup has completed" ); 
            }; 
            Server.ScriptTimeout = 1 * 60 * 60; 
            process.Start(); 
            return new FileStreamResult(process.StandardOutput.BaseStream, "application/backup"); 
    } 
}

您可以尝试使用异步控制器

public class HomeController : AsyncController
{
    public void IndexAsync()
    {
        var process = new Process();
        process.StartInfo.FileName = "c:\\Program Files\\PostgreSql\\9.1\\bin\\pg_dump.exe";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.EnableRaisingEvents = true;
        AsyncManager.OutstandingOperations.Increment();
        process.Exited += (sender, e) =>
        {
            var proc = ((Process)sender);
            string result = null;
            if (proc.ExitCode == 0)
            {
                result = proc.StandardOutput.ReadToEnd();
            }
            else
            {
                result = proc.StandardError.ReadToEnd();
            }
            AsyncManager.Parameters["result"] = result;
            AsyncManager.OutstandingOperations.Decrement();
            Writelog("Backup has completed");
        };
        process.Start();
    }

    public ActionResult IndexCompleted(string result)
    {
        return File(Encoding.UTF8.GetBytes(result), "text/plain");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM