【问题标题】:Background Work does not work in the Foreach function? [closed]后台工作在 Foreach 函数中不起作用? [关闭]
【发布时间】:2013-12-27 00:29:01
【问题描述】:

我的应用程序向CheckedListBox 中的选定组发送消息。我想在程序发送消息时使用Progressbar

foreach (object item in checkedListBox1.CheckedItems) 
{
    if (item.ToString() == gi.name)             //don't read
    {
        if (txtBoxPath.Text == string.Empty)    //don't read
        {
            try
            {
                Dictionary<string, object> args = new Dictionary<string, object>();
                args["message"] = txtBoxStatus.Text;
                fb.Post(gi.id + "/feed", args);

                sCount = checkedListBox1.CheckedItems.Count;
                for (int i = 0; i < sCount; i++)
                {
                    backgroundWrkSendPOST.ReportProgress(100 / sCount); //****HERE****
                }
            }
            catch (FacebookApiException ex)
            {
                MessageBox.Show("ERRO:" + Environment.NewLine + ex.Message, "ERRO", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        else
        {
            .......

其中:sCount(int):表示选中列表框中选中项的数量。 因此,遵循数学规则,对于选择的每个项目 {y}(foreach 函数中的项目)应该乘以 100% / {y},这意味着最终应该是 100%。但是似乎foreach函数不读取后台工作,并且不相乘。

我们调试时的输出:

有人可以帮助我吗?最后,这个进度条应该保持在 100%。

【问题讨论】:

    标签: c# multithreading foreach progress-bar backgroundworker


    【解决方案1】:

    如果我做对了,您检查了 2 个项目 (sCount=2),并且您循环两次 (i&lt;sCount) 以相同的值 (100/2) 调用 ReportProgress

    输出始终为 50,因此 ProgressBar 始终显示为 50 也就不足为奇了

    我会尝试以这种方式更改您的代码

    sCount = checkedListBox1.CheckedItems.Count;
    // Supposing that you could access your ProgressBar in this point
    pBar.Maximum = sCount; 
    pBar.Minimum = 0;
    for (int i = 0; i < sCount; i++)
    {
        backgroundWrkSendPOST.ReportProgress(i); 
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-24
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      • 2017-05-21
      • 2021-03-02
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多