Data Binding and Thread Safety - Why doesn't this work?
attempting bind textbox error logging in windows forms.
bind textbox this:
this.operationeventhistorytextbox.databindings.add("text", this.logger, "operationlog")
logger object instance of logger class, contains following property.
public string operationlog { { return this.operationlog; } set { if (this.operationlog != value) { this.operationlog = value; system.componentmodel.propertychangedeventhandler handler = this.propertychanged; if (handler != null) { handler(this, new system.componentmodel.propertychangedeventargs("operationlog")); } } } }
, error when calling this.logger.logevent("message")
. my logevent
method contains following:
public void logevent(string msg) { this.operationlog += system.datetime.now + ": " + msg + "\r\n"; }
the invalidoperationexception
says there invalid cross-thread operation, , control operationeventhistorytextbox
was accessed thread other thread created on.
understand mean i've written parts of code in way wasn't thread-safe, don't understand why, or fix.
go around setting of these functions invoke rather directly called, i'd understand isn't working.
update: i've attempted use system.threading.scynchronizationcontext
to raise propertychanged event on correct thread, however, continue error. here new setter property:
set { if (this.operationlog != value) { system.threading.synchronizationcontext context = system.threading.synchronizationcontext.current ?? new system.threading.synchronizationcontext(); this.operationlog = value; context.send( (s) => { system.componentmodel.propertychangedeventhandler handler = this.propertychanged; if (handler != null) { handler(this, new system.componentmodel.propertychangedeventargs("operationlog")); } }, null); } }
not correctly creating the synchronizationcontext
? or there else @ work here?
obviously don't think should put synchronizationcontext
setter. check before set value.
chanmm
chanmm
Visual Studio Languages , .NET Framework > Visual C#
Comments
Post a Comment