2012-03-25 73 views
0

以下代碼用於創建備份是在Linux和Windows中的ASP .NET MVC2應用程序。完成後,條目應寫入日誌文件。該代碼將它寫入進程退出事件中。如何檢測發送在MVC控制器中完成

退出事件寫入太早:數據可能無法發送到客戶端。如果發送所有數據,如何寫入日誌事件?流沒有關閉事件。

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"); 
    } 
} 

回答

1

您可以嘗試使用asynchronous controller

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"); 
    } 
} 
+0

在Windows使用這個一樣,pg_dump無法完成並退出事件不會發生。它看起來像發生了死鎖。如何解決這個問題? – Andrus 2012-03-26 08:00:33

+0

也許它只是需要很長時間? – 2012-03-26 08:02:36

+0

號我測試了勝利7快速localhost與8 cpu,數據庫是小的。使用我的原始代碼完成幾秒鐘。如果我將StdError重定向添加到我的原始代碼,則會出現simiral問題。我發佈這個問題在http://stackoverflow.com/questions/9863753/how-to-capture-stderr-of-pg-dump-invoked-from-asp-net-mvc2-controller – Andrus 2012-03-26 08:20:30