简体   繁体   English

秒表是线程安全的吗?

[英]Is the stopwatch thread-safe?

there is a part of my code: 我的代码有一部分:

private void Wait(String expectedResponse)
{
    waitTimeout = 30;
    Stopwatch sw = new Stopwatch();
    sw.Start();
    while (!inputBuffer.Contains(expectedResponse))
    {
        if (sw.Elapsed.Seconds < waitTimeout)
        {
            Thread.Sleep(1);
        }
        else
        {
            sw.Stop();
            throw new Exception("Timeout");
        }
    }
    sw.Stop();
    Console.WriteLine("SUCCESS");
}

The Wait method runs in the main thread and sometimes in the thread that creates the main thread. Wait方法在主线程中运行,有时在创建主线程的线程中运行。

And sometimes the method of program infinitely loops, although the time (30 seconds) has passed, and the exception is not generated. 有时,尽管经过了30秒的时间,但程序的方法仍会无限循环,并且不会生成异常。

So, what's a problem? 那么,有什么问题呢? StopWatch class is not thread-safety? StopWatch类不是线程安全的吗? and if so, how to rewrite the code? 如果是这样,如何重写代码?

Any ideas? 有任何想法吗?

Thank you! 谢谢!

From MSDN : MSDN

Thread Safety 线程安全

Any public static members of this type are thread safe. 此类型的任何公共静态成员都是线程安全的。 Any instance members are not guaranteed to be thread safe. 不保证任何实例成员都是线程安全的。

Also I don't see any thread-sensitive call/method in your codes. 另外,我在您的代码中看不到任何线程敏感的调用/方法。 You're instantiating a thread-local Stopwatch and using it. 您正在实例化一个线程本地的Stopwatch并使用它。 Btw, Thread.Sleep(1) will try to block for 1ms (but this is OS specific, windows will block for ~15ms) and still there is no problem about threads. 顺便说一句, Thread.Sleep(1)将尝试阻塞Thread.Sleep(1)毫秒(但这是特定于操作系统的,Windows会阻塞15毫秒),但是线程仍然没有问题。

Now I think there is a problem with your inputBuffer , why because it's not thread-local. 现在我认为您的inputBuffer存在问题,为什么,因为它不是线程局部的。 If more than one thread tries to use it at the same time, that will cause inconsistency. 如果多个线程试图同时使用它,则将导致不一致。 You may try Stream.Synchronized or implement your own thread-safe stream class. 您可以尝试Stream.Synchronized或实现自己的线程安全的流类。

I also suggest you to use step-by-step debugging or use at least some breakpoints to understand what is going on. 我还建议您使用逐步调试或至少使用一些断点来了解发生了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM