2
我做了一些线程,执行一些工作并运行shutdown.exe来关闭电脑。C#在线程中使用Process.Start
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'll关机。 但是,如果我把它放在使用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;
}
我所说的方法来检查,如果复选框被选中,然后关闭复选框。所以实际上代码没有执行。
你可以尝试把一个断点的DoWork()?这样你可以看到代码是否被执行。你在创建线程后使用“work”吗? C#可能会清除对象,因为它不再被使用。 – Laurence 2012-07-29 17:35:25
你可能将你的线程标记为[后台线程](http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx)('IsBackground = true'),并退出你调用'thread.Start()'之后的过程?一长串,但这会导致你描述的情况。 – 2012-07-29 17:57:30
如果您解决了自己的问题,您可以回答自己的问题并将其标记为已接受,这将使问题不再在每周的头版中显示为“未接受答案”。 – 2012-07-30 04:53:17