c# - Stopwatch elapsed time thread safety -
ok have simple question not find concise answer for. wondering if need worry calling lock() statement when reading elapsed property of stopwatch while still running.
also stopwatch should using measure run-times of thread. have read in other similar questions dispatchtimer used. have looked using events, seemed lot of overhead simple, please inform me if plain wrong , should using events. simple code illustrate talking about.
class foo { private bool _isrunning { get; set; } private stopwatch sw { get; set; } public void startthread() { this._isrunning = true; new thread(new threadstart(this.dowork)).start(); this.sw.restart(); } public void stopthread() { this._isrunning = false; this.sw.stop(); } private void dowork() { while(this._isrunning) { //do stuff } } public timespan getruntime() { return this.sw.elapsed; } public foo() { _isrunning = false; sw = new stopwatch(); } } say in application using above class call getruntime() different thread before stop stopwatch need add lock() statement ensure correct data, , wont blocking stopwatch continuing run. or correct in thinking not need lock() , fine is.
i understand can theoretically run many reads like, curious seeing elapsed properties backing store being written if changed things or not. have read lot of information thread safety, looking clarification , confirmation indeed thinking correctly.
the msdn documentation states, in regard stopwatch, "any instance members not guaranteed thread safe." note there theoretical vulnerability here, uses 'long' tick count internally , updating long on 32-bit processors not atomic operation. can potentially see partially updated (and hence corrupted) values. won't notice until ticks happens run past 32-bit boundary, @ point might run unexpected rare error (you potentially read int32.maxvalue, followed 0, followed int32.maxvalue + 1, yielding large difference in elapsed times if query @ wrong moment.)
Comments
Post a Comment