Thursday, 1 February 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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...