Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIHugging Face LMArena Human Preference 140K

protected override async Task ExecuteAsync(CancellationToken stoppingToken) {…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Kimikimi-k2-0711-preview’s answer.
  1. User

    protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("后台控制台服务启动"); Console.Title = $"白屏自动化,服务器: {authority},工作号:{account}"; while (!stoppingToken.IsCancellationRequested) { await Task.Delay(1000 * 2, stoppingToken); clyg_sgui_cluster_node node = dal.SelectclusterByauthority(authority); if (node == null) { node = new clyg_sgui_cluster_node() { account= account, authority= authority, expired=false, locker=string.Empty, timeout=0, online=true, version= Guid.NewGuid().ToString(), lastcall = DateTimeOffset.Now.ToUnixTimeMilliseconds() }; //添加进去 这种情况是第一次部署新的服务器会出现 dal.Insertcluster(node); } try { Window window = null; Process Process = null; Application app = null; //查状态

             var SguiProcess = Process.GetProcessesByName("共翔天易");
             if (SguiProcess.Length == 0) { Console.WriteLine($"程序未启动或异常关闭,请及时查看!"); isUpdateStart(node.online ? 1 : 0, 0); continue; }
    
             Process = SguiProcess.First();
             app = FlaUI.Core.Application.Attach(Process.Id);
             using (var automation = new UIA3Automation()) 
             {
                 Thread.Sleep(500);
                 window = app.GetMainWindow(automation);
                 Thread.Sleep(500);
    
                 var loginBtn = window.FindFirstDescendant(cf => cf.ByName("登录"));
                 if (loginBtn != null) { SMSHelper.DingSendMessage(dingerrorkey, "通知", $"白屏账号{account}已经失效,请及时查看!!:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}!!!", new List<string>() { }, new List<string>(), false, dingerrortoken); isUpdateStart(node.online ? 1 : 0, 0); continue; }
    
                 //查看定编按钮是否可用
                 var createPnrBtn = window.FindFirstDescendant(cf => cf.ByName("新建PNR"));
                 if (createPnrBtn == null) { SMSHelper.DingSendMessage(dingerrorkey, "通知", $"白屏账号{account}没有检测到新建pnr的按钮,请及时查看问题!!:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}!!!", new List<string>() { }, new List<string>(), false, dingerrortoken); Console.WriteLine("没有检测到新建pnr的按钮,请及时查看问题!"); isUpdateStart(node.online ? 1 : 0, 0); continue; }
    
                 //检测是否有弹窗(登录超时)未登录或登录超时
                 var IsLogin = window.FindFirstDescendant(cf => cf.ByName("未登录或登录超时"));
                 if (IsLogin != null) { SMSHelper.DingSendMessage(dingerrorkey, "通知", $"白屏账号{account}未登录或登录超时,请及时查看!!:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}!!!", new List<string>() { }, new List<string>(), false, dingerrortoken); Console.WriteLine("未登录或登录超时,请及时查看!"); isUpdateStart(node.online ? 1 : 0, 0); continue; }
             } ;
    
             //检查通道号是否更换 这种情况是服务器上更换通道号 或者 服务器白屏登录更换账号 会导致这种问题
             if (node.account != account) 
             {
                 dal.Updateclusteraccount(authority,account);
             }
    
             //正常状态
             isUpdateStart(node.online ? 1 : 0, 1);
         }
         catch (Exception ex) 
         {
             Console.WriteLine(ex.Message);
         }
     }
    

    } 我该如何优化我的程序,减少内容的异常占用,我是用的是FlaUI.UIA3库3.2版本

  2. Assistant

    你这段代码是一个后台服务,定时检查某个进程的UI状态,使用了FlaUI.UIA3 3.2版本。整体逻辑清晰,但有几点可以优化,尤其是资源管理和异常处理,以减少异常占用和潜在的资源泄漏。


    1. 资源释放和using语句

    • 你创建了 Application app = FlaUI.Core.Application.Attach(Process.Id);,但没有释放它。
    • Window window 也没有释放。
    • UIA3Automation 使用了 using,这是对的。
    • Application 和 Window 都实现了 IDisposable,建议用 using 包裹,确保及时释放。

    优化示例:

    try
    {
        var sguiProcesses = Process.GetProcessesByName("共翔天易");
        if (sguiProcesses.Length == 0)
        {
            Console.WriteLine("程序未启动或异常关闭,请及时查看!");
            isUpdateStart(node.online ? 1 : 0, 0);
            continue;
        }
    
        var process = sguiProcesses.First();
        using (var app = Application.Attach(process.Id))
        using (var automation = new UIA3Automation())
        {
            Thread.Sleep(500);
            using (var window = app.GetMainWindow(automation))
            {
                Thread.Sleep(500);
    
                var loginBtn = window.FindFirstDescendant(cf => cf.ByName("登录"));
                if (loginBtn != null)
                {
                    SMSHelper.DingSendMessage(dingerrorkey, "通知", $"白屏账号{account}已经失效,请及时查看!!:{DateTime.Now:yyyy-MM-dd HH:mm:ss}!!!", new List<string>(), new List<string>(), false, dingerrortoken);
                    isUpdateStart(node.online ? 1 : 0, 0);
                    continue;
                }
    
                var createPnrBtn = window.FindFirstDescendant(cf => cf.ByName("新建PNR"));
                if (createPnrBtn == null)
                {
                    SMSHelper.DingSendMessage(dingerrorkey, "通知", $"白屏账号{account}没有检测到新建pnr的按钮,请及时查看问题!!:{DateTime.Now:yyyy-MM-dd HH:mm:ss}!!!", new List<string>(), new List<string>(), false, dingerrortoken);
                    Console.WriteLine("没有检测到新建pnr的按钮,请及时查看问题!");
                    isUpdateStart(node.online ? 1 : 0, 0);
                    continue;
                }
    
                var isLogin = window.FindFirstDescendant(cf => cf.ByName("未登录或登录超时"));
                if (isLogin != null)
                {
                    SMSHelper.DingSendMessage(dingerrorkey, "通知", $"白屏账号{account}未登录或登录超时,请及时查看!!:{DateTime.Now:yyyy-MM-dd HH:mm:ss}!!!", new List<string>(), new List<string>(), false, dingerrortoken);
                    Console.WriteLine("未登录或登录超时,请及时查看!");
                    isUpdateStart(node.online ? 1 : 0, 0);
                    continue;
                }
            }
        }
    
        if (node.account != account)
        {
            dal.Updateclusteraccount(authority, account);
        }
    
        isUpdateStart(node.online ? 1 : 0, 1);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    

    2. 避免Thread.Sleep,改用异步等待

    Thread.Sleep 会阻塞线程,建议改用异步等待:

    await Task.Delay(500, stoppingToken);
    

    3. 减少重复代码,封装通知逻辑

    你多次调用 SMSHelper.DingSendMessage 和 isUpdateStart,可以封装成一个方法:

    private void NotifyAndUpdate(string message, int onlineStatus, int startStatus)
    {
        SMSHelper.DingSendMessage(dingerrorkey, "通知", message, new List<string>(), new List<string>(), false, dingerrortoken);
        isUpdateStart(onlineStatus, startStatus);
    }
    

    调用时:

    NotifyAndUpdate($"白屏账号{account}已经失效,请及时查看!!:{DateTime.Now:yyyy-MM-dd HH:mm:ss}!!!", node.online ? 1 : 0, 0);
    

    4. 捕获更详细异常信息

    当前只打印了 ex.Message,建议打印堆栈信息,方便排查:

    catch (Exception ex)
    {
        Console.WriteLine($"异常: {ex.Message}\n堆栈: {ex.StackTrace}");
        _logger.LogError(ex, "后台服务异常");
    }
    

    5. 避免频繁Attach进程

    如果进程长时间不变,可以考虑缓存 Application 对象,减少 Attach 调用次数,提升性能。


    6. 整体异步优化

    ExecuteAsync 是异步方法,尽量避免阻塞调用,改用异步API:

    await Task.Delay(2000, stoppingToken);
    await Task.Delay(500, stoppingToken);
    

    总结

    • 用 using 释放 Application 和 Window
    • 用异步等待替代 Thread.Sleep
    • 封装重复通知代码
    • 打印详细异常信息
    • 考虑缓存 Application 对象,减少Attach调用
    • 确保所有资源及时释放,避免内存和句柄泄漏

    这样可以显著减少异常占用和资源泄漏,提升程序稳定性和性能。需要我帮你写一版完整优化后的代码示例吗?

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.