更改进程优先级无效

17

我运行一个音频中继应用程序,可以让我同时通过耳机和扬声器播放声音。这个应用程序本身有一个自动设置为“实时”模式的功能,但它只能将其设置为高级,所以现在我必须在任务管理器中手动设置。

我决定自动化这个过程,所以我写了一个小的C#脚本来帮我更改进程优先级(我会在完成后将其添加到启动项)。

namespace ProcessRealtime
{
    class Program
    {
        static void Main(string[] args)
        {
            Process[] processes = Process.GetProcessesByName("audiorepeater");
            foreach (Process proc in processes)
            {
                Console.WriteLine("Changing Priority for: "+proc.Id+" To RealTime");
                proc.PriorityClass = ProcessPriorityClass.RealTime;
                if (proc.PriorityClass == ProcessPriorityClass.RealTime)
                {
                    Console.WriteLine("Worked");
                }
            }
            Console.ReadLine();
        }
    }
}
问题在于它没有应用更改。 桌面截图
有人知道为什么它不起作用吗?

3
嗯,你可以尝试以管理员身份运行你的程序。在某些情况下,这可能是必要的。 - FrostyFire
可以确认@JABFreeware所说的是正确的。 - Simon Whitehead
@Simon Whitehead 谢谢,我添加了一个答案。 - FrostyFire
3个回答

11

你需要以管理员权限运行你的脚本。


我在Win7上进行了测试,分别以管理员身份和普通身份运行Visual Studio。以管理员身份运行可以解决问题(而非管理员身份只能将其设置为高优先级,与原帖中的问题相同)。 - Simon Whitehead
1
谢谢,这是我的疏忽,因为任务管理器似乎不需要管理员权限就可以提高到实时,很酷。只需要找到一种不需要用户干预的方法让它运行(允许以管理员身份运行)。我在考虑将其作为服务来运行。 - Oliver Baker
2
@OliverBaker 如果您是管理员用户,任务管理器可以进行“透明提升”以在不需要UAC提示的情况下提升自身权限。只有由“Microsoft Windows”证书签名的软件才能做到这一点 - Scott Chamberlain

11
尝试这个:
using (Process p = Process.GetCurrentProcess())
    p.PriorityClass = ProcessPriorityClass.High;  

-1

你可以以管理员身份运行或者关闭用户账户控制(UAC),因为你需要权限来访问一个你没有运行的进程。

这对我有效:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// #define DEBUG

namespace ProcessRealtime
{
    class PUBG_RealTime
    {
        static string processName = "TslGame";
        static ProcessPriorityClass newPriority = ProcessPriorityClass.High;

        static void Main(string[] args)
        {
#if DEBUG
            PutDebug("Start!");
#endif
            Process[] processes = Process.GetProcessesByName(processName);
#if DEBUG
            PutDebug(processes.Length + " processed found");
#endif
            foreach (Process proc in processes)
            {
#if DEBUG
                PutDebug("New process found");
#endif
                Console.WriteLine("Changing Priority for id:" + proc.Id + " to " + newPriority.ToString());
                proc.PriorityClass = newPriority;
#if DEBUG
                PutDebug("Changed priority for " + proc.Id);
#endif
            }
#if DEBUG
            PutDebug("No more processes..");
#endif
            Console.Write("Press a key, it's over !");
            Console.ReadLine();
        }

#if DEBUG
        static bool debug = true;
        static int debugInc = 1;
        static void PutDebug(string info = "")
        {
            if(debug){
                Console.WriteLine("Debug" + debugInc + ": " + info);
                debugInc++;
            }
        }
#endif
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接