winforms 系统异步执行后台任务时的Windows窗体进度条

tf7tbtn2  于 2023-04-12  发布在  Windows
关注(0)|答案(1)|浏览(124)

使用Windows窗体,我想编写一个读取SIM卡的onclick事件。此函数使应用程序在5000毫秒内无响应。
我想同时运行这两个函数,彼此独立

private  void button1_Click(object sender, EventArgs e)
{           
    // run both functions at the same time  
    barraProgresso(5000);         // progress bar          
    run_background_function();    // renders app unresponsive
}

private void barraProgresso(int tempo)
{
    for (int progresso = 0; progresso <= 100; progresso++)
    {
        progressBar1.Value = progresso;
        Thread.Sleep(tempo / 100);
    }
}

谢谢大家。

jq6vz3qz

jq6vz3qz1#

下面是一个例子,它模拟了正在进行的工作沿着取消选项。

模拟在窗体的单独类中完成的工作。

public class Operations
{
    public static async Task AsyncMethod(IProgress<int> progress, CancellationToken cancellationToken)
    {

        for (int index = 0; index <= 100; index++)
        {
            // Simulate an async call that takes some time
            // to complete like uploading a file
            await Task.Delay(100, cancellationToken);

            if (cancellationToken.IsCancellationRequested)
            {
                cancellationToken.ThrowIfCancellationRequested();
            }

            progress?.Report(index);
        }
    }
}

表格代码

public partial class Form1 : Form
{
    private CancellationTokenSource _cancellationTokenSource = 
        new CancellationTokenSource();
    public Form1()
    {
        InitializeComponent();
    }

    private async void StartButton_Click(object sender, EventArgs e)
    {
        progressBar1.Value = 0;

        var cancelled = false;

        if (_cancellationTokenSource.IsCancellationRequested)
        {
            _cancellationTokenSource.Dispose();
            _cancellationTokenSource = new CancellationTokenSource();
        }

        var progressIndicator = new Progress<int>(ReportProgress);

        try
        {
            await Operations.AsyncMethod(progressIndicator, _cancellationTokenSource.Token);
        }
        catch (OperationCanceledException ex)
        {
            cancelled = true;
        }

        if (cancelled)
        {
            MessageBox.Show("Cancelled");
        }
    }

    private void CancelOperationButton_Click(object sender, EventArgs e)
    {
        _cancellationTokenSource.Cancel();
    }

    private void ReportProgress(int value)
    {
        progressBar1.Increment(1);
        LblPercent.Text = $"{value} %";
    }
}

相关问题