c#WPF进度条更新

时间:2016-06-14 18:30:53

标签: c# wpf

所以我有这个进度条,我正在改变每次睡眠后的价值。有没有什么方法可以让Progress Bar直观地更新,而不是只是坐在0%并且在执行结束时跳到100%?

private Client getConnectionPDU()

    {

        // Client à retourné
        PrimS.Telnet.Client client = null;

        // Ouverture de la connection
        try
        {
            // --- Ouverture de la connexion
            client = new Client(rackToIP[selectedRack], addrPort, new System.Threading.CancellationToken());
            console.Text +=  client.Read();
            Thread.Sleep(sleep);
            progressBar.Value = 20;

            // --- Username
            client.WriteLine(username + enter);
            Thread.Sleep(sleep);
            progressBar.Value = 40;

            console.Text += "\n" + client.Read();
            Thread.Sleep(sleep);
            progressBar.Value = 60;

            // --- Password
            client.WriteLine(password + enter);
            Thread.Sleep(sleep);
            progressBar.Value = 80;
            console.Text += "\n" + client.Read();
            Thread.Sleep(sleep);
            progressBar.Value = 100; 

        }
        catch (Exception e)
        {
            console.Text += "\n" + e.Message;
            client = null;
        }

        // Scroll to end
        scroller.ScrollToEnd();

        return client;
    }

2 个答案:

答案 0 :(得分:1)

您的代码阻止了UI线程,从未让它有机会以新的大小重绘进度条,直到函数返回为止。您应该考虑使用async / await来避免阻止。

您需要进行一些更改才能正常工作:

  • 将所有Thread.Sleep来电更改为await Task.Delay
  • 更改getConnectionPDU以返回Task<Client>
  • getConnectionPDU标记为async

假设您的代码是通过单击按钮调用的,结果将如下所示(未经过测试,可能包含错误):

private async void Button1_click(object sender, EventArgs e)
{
    var TheClient = await getConnectionPDU();
}

private async Task<Client> getConnectionPDU()
{

    // Client à retourné
    PrimS.Telnet.Client client = null;

    // Ouverture de la connection
    try
    {
        // --- Ouverture de la connexion
        client = new Client(rackToIP[selectedRack], addrPort, new System.Threading.CancellationToken());
        console.Text +=  client.Read();
        await Task.Delay(sleep);
        progressBar.Value = 20;

        // --- Username
        client.WriteLine(username + enter);
        await Task.Delay(sleep);
        progressBar.Value = 40;

        console.Text += "\n" + client.Read();
        await Task.Delay(sleep);
        progressBar.Value = 60;

        // --- Password
        client.WriteLine(password + enter);
        await Task.Delay(sleep);
        progressBar.Value = 80;
        console.Text += "\n" + client.Read();
        await Task.Delay(sleep);
        progressBar.Value = 100; 

    }
    catch (Exception e)
    {
        console.Text += "\n" + e.Message;
        client = null;
    }

    // Scroll to end
    scroller.ScrollToEnd();

    return client;
}

答案 1 :(得分:1)

我建议使用backgroundWorker线程。以下是您尝试执行的操作的类似问题: How to correctly implement a BackgroundWorker with ProgressBar updates?