简体   繁体   English

由Visual Studio自动生成的代码是否是线程安全的?

[英]Is code that's generated automatically by Visual Studio thread-safe?

I'm learning C#. 我正在学习C#。 Sorry for the newbie question. 对不起,新手问题。

This is part of some code that's automatically generated by Visual Studio 2015 when I start a Windows Forms project. 这是启动Windows Forms项目时Visual Studio 2015自动生成的某些代码的一部分。 It's in Form1.Designer.cs 在Form1.Designer.cs中

    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

I'm trying to see if I understand the concept of thread-safety correctly. 我试图查看我是否正确理解了线程安全性的概念。 Isn't it possible for components to be set to null between the time the if statement is evaluated and the time components.Dispose() is called? 在评估if语句与调用components.Dispose()的时间之间,是否不可能将components设置为null

Thanks in advance for any help understanding this! 在此先感谢您对理解此问题的任何帮助!

No, it's not thread-safe code. 不,这不是线程安全的代码。 Your assumption is correct that components could become null between the check and the Dispose . 您的假设是正确的,即在check和Dispose之间components 可能为空。

However, that doesn't mean it's bad code. 但是,这并不意味着它是错误的代码。 Not all code needs to be thread-safe. 并非所有代码都必须是线程安全的。 If two threads were disposing the same object, it's very likely that that behaviour is a bug, rather than Dispose being erroneous. 如果两个线程都在处理同一个对象,则行为很可能是错误,而不是错误地Dispose

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

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