C# - Alternative to Thread.Sleep?

前端 未结 4 1928
失恋的感觉
失恋的感觉 2021-01-26 17:13

I\'m doing all this in C#, in Visual Studio 2008.

I want to slow down the work of my algorithm so that the user can watch it\'s work. There is a periodic change visible

4条回答
  •  北恋
    北恋 (楼主)
    2021-01-26 18:01

    This depends on a lot of things, so its hard to give a concrete answer from what you've said. Still, here are some matters that might be relevant:

    Are you doing this on a UI thread (e.g. the thread the form-button or UI event that triggered the work started on)? If so, it may be better to create a new thread to perform the work.

    Why do you sleep at all? If the state related to the ongoing work is available to all relevant threads, can the observer not just observe this without the working thread sleeping? Perhaps the working thread could write an indicator of the current progress to a volatile or locked variable (it must be locked if it's larger than pointer size - e.g. int or an object - but not otherwise. If not locked, then being volatile will prevent cache inconsistency between CPUs, though this may not be a big deal). In this case you could have a forms timer (there are different timers in .Net with different purposes) check the status of that variable and update the UI to reflect the work being done, without the working thread needing to do anything. At most it may be beneficial to Yield() in the working thread on occasion, but its not likely that even this will be needed.

提交回复
热议问题