簡體   English   中英

在兩個不同類之間使用后台工作程序的進度欄

[英]Progress Bar using Background worker between two different classes

  1. 我在Visual Studio(2010版)中工作。
  2. 我試圖基於另一名稱空間和類中的變量以一種形式(不同的名稱空間和類)設置進度條。
  3. 您在代碼中看到的ProgressPerc變量來自另一個類(我已經使用'OtherNameSpace'進行了指示。
  4. 它告訴我我無法將ProgressPerc轉換為int(因為我無法將類型轉換為int int)。

這里最最佳的解決方案是什么? 我想使用此變量來指示仿真的進度。

編輯:添加了ALMBerekeningen代碼。 這只是其中的一小部分,完整的代碼太多了,無法在此處顯示。

謝謝!


public class ALMBerekeningen
{
    public int sim;
    public int Progress;
    public double ProgressPerc;

    this.ProgressPerc = this.sim / 1000;
    this.Progress = (int)Math.Round(this.Progress * 100f, 0, MidpointRounding.AwayFromZero);
}

Public class Form1: Form
{
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {

        ALMBerekeningen ProgressPerc;

        int sims;

        sims = (int)ProgressPerc;

        try
        {
            backgroundWorker1.ReportProgress(sims);
        }

        catch (Exception ex)
        {
            backgroundWorker1.CancelAsync();
            MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
        lblProgress.Text = "Completed " + progressBar1.Value.ToString() + " %";
        progressBar1.Update();
    }
}

您需要在啟動時將ALMBerekeningen實例ALMBerekeningen給后台工作程序,然后使用事件處理程序中的DoWorkEventArgs.Argument屬性對其進行訪問:

public void Main()
{
     //The instance of the class with the variable for your progress bar
     ALMBerekeningen almBerekeningen = new ALMBerekeningen();

     BackgroundWorker bgw = new BackgroundWorker();
     bgw.DoWork += bgw_DoWork;

     //Pass your class instance in here
     bgw.RunWorkerAsync(almBerekeningen);
}


private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{

    //e.Argument is the instance of the class you passed in
    var progressPerc = (ALMBerekeningen)e.Argument;

    int sims;

    sims = progressPerc.ProgressPerc;

    try
    {
        backgroundWorker1.ReportProgress(sims);
    }

    catch (Exception ex)
    {
        backgroundWorker1.CancelAsync();
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

附帶地,您顯示的DoWork處理程序將只執行一次。 我認為您只是為了示例而將其簡化了下來。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM