c# - BackgroundWorker questions -
i have ui wpf application.
may 1 have ideas why code not working?
case 1:
backgroundworker worker = new backgroundworker(); worker.dowork += delegate { //some logic }; worker.runworkerasync();
in case getting exception calling thread cannot access object because different thread owns it. changed this:
backgroundworker worker = new backgroundworker(); worker.dowork += delegate { this.dispatcher.begininvoke( new action(() => { //my code here }), null); };
after ui getting frozen during executing code. executing in same thread
case 2:
backgroundworker worker = new backgroundworker(); worker.runworkerasync(new action(() => { //some code here }));
in case code inside action not executed.
//----------------------------------updated--------------------------------------//
thank guy's reason why code didn't work mentioned below. did access ui elements in background thread. getting values ui elements before call backgroundworker. declare new variables, assign them values required ui elements, , passing these variables backgroundworker instead of ui elements (which did).
the problem first version inside "some logic" accessing wpf objects - can't that, wpf objects can accessed same thread created them.
the problem second version starting background thread asks main thread work , exits, doing work on main thread (that ui work) , ui freezes, equivalent not using backgroundworker @ all.
the third version, jon skeet said, simple incorrect usage , isn't supposed work think is.
so, need do?
you need collect information ui in main thread before starting background worker, can use simple types (string, int, double, etc.) , thread-safe classes/structs, can not use wpf classes in code executed backgroundworker.
after finished collecting data can call runworkerasync, in dowork handler can not read data ui - can access data prepared before, can not write ui - have save somewhere else (class member example) , copy ui after backgroundworker finished.
the exception "can't access wpf thread" rule freezable (and classes inherit freezable) after freeze method called, makes object read-only , thread-safe.
Comments
Post a Comment