qshinoの日記

Powershell関係と徒然なこと

Exited Event非同期対応

Start-ProcessのExitedEvent Thread

Strart-ProcessのExited EventはデフォルトではSystem thread pool から実行される。UI系とは異なるため、UI系を制御すると問題が発生しやすい。

そのため、Formなどで使用するためにSynchronizingObject にUIオブジェクトを設定する。

this.process1.StartInfo.Domain = "";
this.process1.StartInfo.LoadUserProfile = false;
this.process1.StartInfo.Password = null;
this.process1.StartInfo.StandardErrorEncoding = null;
this.process1.StartInfo.StandardOutputEncoding = null;
this.process1.StartInfo.UserName = "";
this.process1.SynchronizingObject = this;

使用例

ここでは、ボタン自身をSynchronized Objectに設定している。

   private MyButton button1;
   private void button1_Click(object sender, System.EventArgs e)
   {
      Process myProcess = new Process();
      ProcessStartInfo myProcessStartInfo= new ProcessStartInfo("mspaint");
      myProcess.StartInfo = myProcessStartInfo;
      myProcess.Start();
      myProcess.Exited += new EventHandler(MyProcessExited);
      // Set 'EnableRaisingEvents' to true, to raise 'Exited' event when process is terminated.
      myProcess.EnableRaisingEvents = true;
      // Set method handling the exited event to be called  ;
      // on the same thread on which MyButton was created.
      myProcess.SynchronizingObject = button1;   // ここで自身を設定
      MessageBox.Show("Waiting for the process 'mspaint' to exit....");
      myProcess.WaitForExit();
      myProcess.Close();
   }
   private void MyProcessExited(Object source, EventArgs e)
   {
      MessageBox.Show("The process has exited.");
   }
}

public class MyButton:Button
{

}

参考

https://msdn.microsoft.com/ja-jp/library/system.diagnostics.process.synchronizingobject(v=vs.110).aspx

http://dobon.net/vb/dotnet/process/openfile.html

毛並みが異なるが、Window.Formsのイベント

http://d.hatena.ne.jp/newpops/touch/20070120/p1

普通のイベント

http://blog.okazuki.jp/entry/2014/08/22/211021

System.Windows.Threading.DispatcherTimer in WindowsBase assembly

https://msdn.microsoft.com/ja-jp/library/ms615945.aspx#継承階層