我创建了一个线程来做一些工作并运行 shutdown.exe 来关闭电脑。
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() 将其放入线程中,电脑将不会关闭。
编辑: 发现我的错误。我创建了一个线程安全的调用方法来读取总是返回 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;
}
我调用该方法来检查复选框是否被选中然后关闭。所以实际上代码并没有被执行。
最佳答案
如果要关闭计算机,最好调用 Win32 的 ExitWindows
函数,而不是运行 shutdown.exe
程序。
这里有 MSDN 文档:http://msdn.microsoft.com/en-us/library/windows/desktop/aa376867%28v=vs.85%29.aspx
这里是 C# P/Invoke 签名:http://www.pinvoke.net/default.aspx/user32.exitwindowsex
关于C# 在线程中使用 Process.Start,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11711367/