c# - Cross-thread operation not valid when using Invoke -
i've made chat system , got error:
cross-thread operation not valid: 'messagebox' etc.
what have done: i've added invoke. here code:
invoke(new action(() => messagebox.items.add(usersname.text + ": " + receivedmessage)));
the problem is, sends message other user blank. because i'm connected chat locally. here picture:
receiving messages:
private void messagecallback(iasyncresult aresult) { try { byte[] receiveddata = new byte[1500]; receiveddata = (byte[])aresult.asyncstate; asciiencoding aencoding = new asciiencoding(); string receivedmessage = aencoding.getstring(receiveddata); invoke(new action(() => messagebox.items.add(usersname.text + ": " + receivedmessage))); buffer = new byte[1500]; socket.beginreceivefrom(buffer, 0, buffer.length, socketflags.none, ref theirip, new asynccallback(messagecallback), buffer); } catch (exception ex) { messagebox.show(ex.message); } }
sending messages:
private void sendbtn_click(object sender, eventargs e) { try { if (messagetb.text == "") { return; } else { asciiencoding eencoding = new asciiencoding(); byte[] msg = new byte[1500]; msg = eencoding.getbytes(messagetb.text); socket.send(msg); messagebox.items.add(yourname.text + ": " + messagetb.text); messagetb.clear(); } } catch (exception ex) { messagebox.show(ex.message); } this.activecontrol = messagetb; }
this exception occurs whenever trying access control in different thread other form's main thread.
i use bellow simple log mechanism, suitable simple application.
private delegate void logdelegate(listbox messagebox, string data); private logdelegate _logdelegate; private void log(listbox messagebox, string data) { if (messagebox.invokerequired) { logdelegate logdelegate = log; invoke(logdelegate, messagebox, data); } else { messagebox.items.add(data); } } public form1() { initializecomponent(); //don't forget, initialize delegate _logdelegate = log; } private void btn_start_click(object sender, eventargs e) { log("anything log"); } private void messagecallback(iasyncresult aresult) { try { //instead of invoke use //invoke(new action(() => messagebox.items.add(usersname.text + ": " + receivedmessage))); log("anything log"); } catch (exception ex) { messagebox.show(ex.message); } }
as said, code can used anywhere , simple. more complex logging mechanism , better performing use log4net or nlog.
Comments
Post a Comment