gpt4 book ai didi

c# - 在两个不同的类之间使用后台 worker 的进度条

转载 作者:行者123 更新时间:2023-12-04 17:02:14 25 4
gpt4 key购买 nike

  • 我在视觉工作室(2010 版)工作。
  • 我正在尝试基于另一个命名空间和类中的变量以一种形式(不同的命名空间和类)设置进度条。
  • 您在代码中看到的 ProgressPerc 变量来自另一个类(我已经使用“OtherNameSpace”指出了这一点。
  • 它告诉我我无法将 ProgressPerc 转换为 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的实例当您启动它时到后台工作人员,然后使用 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如图所示的处理程序只会执行一次。我认为您只是为了示例而将其简化了。

    关于c# - 在两个不同的类之间使用后台 worker 的进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45330669/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com