[英]Backgroundworker progresschanged event c#
I am using background worker in winforms. 我在winforms中使用后台工作者。 In
backgroundworker_progresschanged
event e.userstate
is a item which is to be added in the listbox
. 在
backgroundworker_progresschanged
事件中, e.userstate
是要添加到listbox
。 At the same time I want to show the e.userstate
on the popup window. 同时,我想在弹出窗口中显示
e.userstate
。
Here is my code: 这是我的代码:
In backgroundworker_progresschanged
event setlable()
is a method which is from the another class. 在
backgroundworker_progresschanged
事件中, setlable()
是另一个类的方法。
public void SetLable(string pbValue)
{
try
{
label1.Text = pbValue;
}
catch (Exception ex)
{ }
label1.ForeColor = Color.Red;
}
I want to add userstate
in listbox2
and at the same time want to show that on popup window which i have created in another form. 我想在
listbox2
添加userstate
,同时要在以其他形式创建的弹出窗口中显示该状态。 I have comment out the listbox.items.add
because both are not working at the same time. 我已将
listbox.items.add
注释掉,因为两者不能同时工作。
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
List<string> result1 = new List<string>();
var found = obj.getFiles();
foreach (var item in found)
{
if (item.Contains("ERROR"))
{
result1.Add(item);
(sender as BackgroundWorker).ReportProgress(0, item);
}
else
(sender as BackgroundWorker).ReportProgress(0);
System.Threading.Thread.Sleep(500);
}
e.Result = result1;
}
private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState != null)
pop.SetLable(e.UserState.ToString());
// listBox2.Items.Add(e.UserState);
}
I want both to be work at same time. 我希望两个人同时工作。
pop.SetLable(e.UserState.ToString());
// listBox2.Items.Add(e.UserState);
Is this possible? 这可能吗?
An if statement only executes the statement immediately following it. if语句仅执行紧随其后的语句。 If you intend for more than one thing to occur, use a block:
如果您打算发生多件事,请使用一个块:
private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState != null)
{
pop.SetLable(e.UserState.ToString());
listBox2.Items.Add(e.UserState.ToString());
}
}
Get into the habit of immediately typing both brackets in when you create every single if statement (same goes for any else portions!). 养成在创建每个if语句时立即在两个方括号中输入的习惯(其他部分都一样!)。 Even single statements should be enclosed in a block for if/else statements...that way you can add things to your logic later and not fall into this type of subtle bug.
即使单个语句也应该包含在if / else语句的块中...这样,您以后就可以在逻辑中添加内容,而不会陷入这种细微的错误中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.