Csharp 异步轮询例子

using System;
using System.Threading.Tasks;
using System.Windows.Forms;

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
        // 窗体加载时自动开始轮询
        this.Load += async (sender, e) => await StartPollingWithRetryAsync();
    }

    // 启动轮询的公共方法
    public async Task StartPollingWithRetryAsync()
    {
        const int maxRetryCount = 3;
        int attemptCount = 0;
        bool userWantsToContinue = true;

        while (userWantsToContinue)
        {
            attemptCount = 0; // 重置尝试计数器
            
            // 尝试最多3次
            while (attemptCount < maxRetryCount)
            {
                attemptCount++;
                
                try
                {
                    // 执行判断逻辑
                    bool conditionMet = await CheckConditionAsync();
                    
                    if (conditionMet)
                    {
                        UpdateStatus($"条件满足,操作成功 (尝试 {attemptCount} 次)");
                        return; // 条件满足,退出方法
                    }
                    
                    UpdateStatus($"条件未满足,等待重试... (尝试 {attemptCount}/{maxRetryCount})");
                }
                catch (Exception ex)
                {
                    UpdateStatus($"尝试 {attemptCount} 发生错误: {ex.Message}");
                }
                
                // 固定等待1秒
                await Task.Delay(1000);
            }
            
            // 3次尝试后仍未满足条件,询问用户
            var dialogResult = MessageBox.Show(
                "操作未成功完成,是否继续等待并重试?", 
                "询问", 
                MessageBoxButtons.YesNo, 
                MessageBoxIcon.Question);
            
            userWantsToContinue = (dialogResult == DialogResult.Yes);
            
            if (!userWantsToContinue)
            {
                UpdateStatus("用户选择终止操作,程序将退出");
                Application.Exit();
                return;
            }
            
            UpdateStatus("用户选择继续,开始新一轮尝试...");
        }
    }

    // 模拟异步条件检查
    private async Task<bool> CheckConditionAsync()
    {
        // 这里替换为实际的判断逻辑
        await Task.Delay(300); // 模拟异步操作
        
        // 模拟随机结果 - 实际应用中替换为你的判断逻辑
        Random rnd = new Random();
        return rnd.Next(0, 10) > 7; // 30%概率返回true
    }

    // 更新UI状态
    private void UpdateStatus(string message)
    {
        if (InvokeRequired)
        {
            Invoke(new Action<string>(UpdateStatus), message);
            return;
        }
        
        lblStatus.Text = $"[{DateTime.Now:HH:mm:ss}] {message}";
        txtLog.AppendText($"{lblStatus.Text}{Environment.NewLine}");
    }
}

引用方式

1.其他类直接调用

// 在其他类中调用轮询
var mainForm = new MainForm();
await mainForm.StartPollingWithRetryAsync();

2.窗体中调用

// 在窗体构造函数中
this.Load += async (sender, e) => await StartPollingWithRetryAsync();

 

posted @ 2025-07-15 19:39  尼古拉-卡什  阅读(16)  评论(0)    收藏  举报