Thursday, February 1, 2018

c# - Cross-thread operation not valid: Control 'listBox1' accessed from a > thread other than the thread it was created on











While I am trying to add items to a ListBox, I'am getting the following error:





Cross-thread operation not valid: Control 'listBox1' accessed from a
thread other than the thread it was created on.




Here is tried code:



private void Form1_Load(object sender, EventArgs e)
{

Jid jd = new Jid("USERNAME");
xmpp.Open(jd.User, "PASSWORD");
xmpp.OnLogin += new ObjectHandler(xmpp_OnLogin);
agsXMPP.XmppConnection p;
xmpp.OnPresence += new PresenceHandler(xmpp_OnPresence);
}
void xmpp_OnPresence(object sender, Presence pres)
{
listBox1.Items.Add(pres.From .User ); --- **HERE I AM GETTING ERROR.**
}



I am little bit new in C# and also with threading, I googled and checked many articles including SO, But still I don't know how to solve the problem.


Answer



Try this out



void xmpp_OnPresence(object sender, Presence pres)
{
this.Invoke(new MethodInvoker(delegate()
{


listBox1.Items.Add(pres.From .User ); --- **HERE I AM GETTING ERROR.**

}));
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...