いくつかの作業を行うスレッドを作成し、shutdown.exe を実行して PC をシャットダウンします。
Worker work = new Worker();
Thread thread = new Thread(new ThreadStart(work.DoWork));
thread.Start();
およびメソッド DoWork()
public void DoWork()
{
/* Do some thing */
// This will shutdown the PC
ProcessStartInfo startInfo = new ProcessStartInfo(Environment.GetFolderPath(System.Environment.SpecialFolder.System) + @"\shutdown.exe", "-s -t 5");
Process.Start(startInfo);
}
メイン スレッドでメソッド work.DoWork() を呼び出すと、PC がシャットダウンします。しかし、thread.Start() を使用してスレッドに入れると、PC はシャットダウンしません。
編集:間違いを見つけました。常にfalseを返すチェックボックスを読み取るためのスレッドセーフな呼び出しメソッドを作成します
delegate bool GetcbShutdownCheckedValueCallback();
public bool GetcbShutdownCheckedValue()
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.lblCraftRemain.InvokeRequired)
{
GetcbShutdownCheckedValueCallback d = new GetcbShutdownCheckedValueCallback(GetcbShutdownCheckedValue);
this.Invoke(d);
}
else
{
return cbShutdown.Checked;
}
return false;
}
メソッドを呼び出して、チェックボックスがオンになっているかどうかを確認してからシャットダウンします。したがって、実際にはコードは実行されません。