C# 在线程中使用 Process.Start

标签 c# winforms multithreading

我创建了一个线程来做一些工作并运行 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/

相关文章:

c# - 多字段索引对象数组

c# - 在启动时加载所有本地化资源

c# - 如何在选择 1 时取消选择其他列表框

c - 使函数线程安全 : Thread-specific data vs mutex

c++ - 原子读然后用 std::atomic 写

c# - 如何从我的 C 代码调用 C# dll 中的方法?

c# - 淡入/淡出图像的最佳方式

c# - 确定数组与目标数组的接近程度

WinForms 的 iPhone UI 控件

java - Java中最快的循环同步是什么(ExecutorService vs. CyclicBarrier vs. X)?