c# - Is it possible to wrap specific classes or methods and assign them to a thread? -
i have xaml form 2 independent features threaded out of main xaml execution thread: 1.) timer control ticks up, , 2.) implement pause button can freeze set of procedural set of activities , clicking on pause button again resume.
when start form, entire app freezes. because of can't interact btnpause control. got timer class work, (lbltimer) updates in chunks, or whenver looks cpu isn't busy on main thread.
i tried create class "task" wraps class or method in own thread can control.
automation.task automationthread = new automation.task(); automation.task timerthread = new automation.task();
later on, attempted create stopwatch class , assign timerthread can manage independently.
automation.watchtimer stopwatch = new automation.watchtimer(lbltimer, timerthread); class task { private manualresetevent _shutdownflag = new manualresetevent(false); private manualresetevent _pauseflag = new manualresetevent(true); thread _thread; public task() { } public void start() { _thread = new thread(dowork); _thread.start(); } public void resume() { _pauseflag.set(); } public void stop() { _shutdownflag.set(); _pauseflag.set(); _thread.join(); } public void dowork() { { _pauseflag.waitone(timeout.infinite); } while (!_shutdownflag.waitone(0)); } // not sure if right approach public void dowork(func<void> method????) { { // not sure put here // want method // wraps long chain of procedural items // can pause (block) , unpause through ui } while (!_shutdownflag.waitone(0)); } class watchtimer { public watchtimer(system.windows.controls.label lbl, automation.task worker) { lblfield = lbl; worker.start(); } private system.windows.controls.label lblfield; timer time = new timer(); stopwatch sw = new stopwatch(); public void start() { time.start(); sw.start(); time.tick += new eventhandler(time_tick); } public void stop() { time.stop(); sw.stop(); } public void reset() { sw.reset(); lblfield.content = this.elapsedtime(); } public string elapsedtime() { timespan ts = sw.elapsed; // return formatted timespan value return string.format("{0:00}:{1:00}:{2:00}.{3:00}", ts.hours, ts.minutes, ts.seconds, ts.milliseconds); } private void time_tick(object sender, eventargs e) { lblfield.content = this.elapsedtime(); } }
the timer appears work, still spits updates in chunks - mean it's not on own thread?
the apparent hang caused because 1 cpu pegged @ 100%. because initial state of _pauseflag
set signaled. when main thread calls new thread(dowork)
, dowork
blowing past _pauseflag.waitone
, running in tight do/while
loop.
to wrap method in thread, pausing, doable. have remove do/while
dowork
method. sequential code in dowork
have check paused event signaled state, in between subtasks, inner loops, or whatever have in sequential work method.
Comments
Post a Comment