Should I block even when I'm sequentially processing

我的未来我决定 提交于 2019-12-02 07:36:31

I'd either go all-out thread safe or do no thread safety at all and just write in your documentation very clearly that the class isn't thread safe.

The worst thing is coming back a couple years later and not remembering whether or not everything's safe. Then you end up wasting a lot of time investigating your code, or worse, you end up misleading yourself.

You only need to lock if more than a single thread will be working with the objects. In your case, your design prevents that from ever occurring, so there is no need to lock.

The only real advantage to adding the lock, in this case, would be to prevent issues from occurring if you later change your scheduling algorithm.

Like the others have said, if its a single thread, no need for the lock. Also, you could skip the timer all together:

        TimeSpan maxInterval = new TimeSpan(0, 10, 0);
        while(true)
        {
            DateTime startTime = DateTime.UtcNow;


            //Do lots and lots of work


            TimeSpan ts = DateTime.UtcNow - startTime;
            ts = (ts > maxInterval ? new TimeSpan(0) : maxInterval-ts);
            Thread.Sleep(ts);
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!