简体   繁体   English

ASP.net C#中的此静态变量线程安全吗?

[英]Is this static variable thread safe in ASP.net c#

I know this kind of thing has been asked many times on here but I'm still not completely understanding thread safety in ASP. 我知道这种事情在这里已经被问过很多遍了,但是我仍然没有完全理解ASP中的线程安全性。

C#: Where Util is a static class and theList is a static List. C#:其中Util是静态类,而List是静态列表。

Util.theList= new List<Object>();
 Util.theList.Add(someObject);

The page loads once, then a second later(1 SECOND AFTER POSTBACK) the Util.theList is populated and the page is reloaded to bind with newly populated list data: 该页面加载一次,然后再填充一秒钟(在回发后第二秒),将Util.theList填充,并重新加载页面以与新填充的列表数据绑定:

this.Repeater.DataSource = Util.theList;
            this.Repeater.DataBind();

Each time theList is populated it is INSTANTIATED: 每次填充列表时,它都是实例化的:

Util.theList= new List<Object>(); 

If this is not thread safe how can I make it thread safe? 如果这不是线程安全的,我如何使其成为线程安全的? I can't have the list non static and on the same page because of a separate problem where the data only binds each time if it is bound on page_load: OnDataBind only fires on first postback 由于一个单独的问题,数据每次绑定到page_load时才绑定,所以我不能在同一页面上使用非静态列表: OnDataBind仅在第一次回发时触发

It is clearly unsafe because static variables are shared between requests. 这显然是不安全的,因为在请求之间共享静态变量。 Move the list to some place that is unique to a particular request, like a page instance field. 将列表移动到特定请求所独有的某个位置,例如页面实例字段。

If you need to pass state across postbacks use ViewState or some other non-global mechanism. 如果您需要在回发之间传递状态,请使用ViewState或其他一些非全局机制。

Its best if you avoid static variables all together. 最好是同时避免使用静态变量。 Static variables do not really fit well with unit testing. 静态变量并不真正适合单元测试。 Static classes and variables cannot be stubbed or mocked. 不能对静态类和变量进行存根或模拟。

However, in your instance, no the static variables are not thread safe. 但是,在您的实例中,没有静态变量不是线程安全的。

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

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