c# - Generic BeginInvoke Scheme to ensure function calls in same threading context -
i'm moving code winforms command object separate object improve modularity. however, there calls external object issuing callbacks, have no command of , can fired different threads main ui thread. avoid utilize known begininvoke scheme check, whether phone call should transfered main ui thread.
when move code separated object, have not necessary winforms reference anymore. handle on command object still ensure running in same thread. rather have generic mechanism same ensuring, threadconext in e.g. object created or specific entry function called used subsequent calls issued e.g. external callbacks.
how achieved ?
example:
public class illustration { threadedcomponent _cmp = new threadedcomponent(); public example() { _cmp.threadedcallback += new threadedcomponent.cb(callback); } public void startfunction() { // called in threadcontexta _cmp.start(); } void callback(status s) { // called in threadcontextb if(s == somestatus) _cmp.continuefunction(); // must called in threadcontexta } }
for clarification
continuefunction
must called same threadcontext startfunction
called. not ui thread, @ moment of course of study button handler.
there no 'generic' scheme, class cannot create lot of assumptions thread used on , object can provide begininvoke() method need. take 1 of next options:
do not help @ all, document event can raised on worker thread. whatever code exists in gui layer can of course of study figure out how utilize begininvoke() when needed.
allow client code pass command object through class constructor. can store , phone call begininvoke() method. works, isn't terribly pretty because class usable in winforms project.
expose property called "synchronizingobject" of type isynchronizeinvoke. gui layer has option inquire phone call isynchronizeinvoke.begininvoke(). if property set, fire event straight otherwise. several .net framework classes this, process, filesystemwatcher, eventlog, etc. has same problem previous solution, interface isn't readily available in non-winforms application.
demand client code creates object on ui thread. , re-create synchronizationcontext.current in constructor. can, later, utilize post() method invoke. compatible option, gui class libraries in .net provide value property.
do maintain problem in mind when take 1 of latter bullets. client code event unsynchronized thread's code execution. concrete event handler want access properties on class find out more state of class. state unlikely still valid since thread has progressed past begininvoke() call. client code has no alternative @ insert lock prevent causing trouble. should consider not help @ if that's real issue, is.
c# .net multithreading thread-safety
No comments:
Post a Comment