Is it safe to use C# global variables in a background worker thread

感情迁移 提交于 2019-12-07 09:42:44

问题


Hi I am working on a simple desktop application, it needs to handle some operations like loading a webpage which may block the main thread, so i moved the code to a background worker.

My problem is there is a heavy class named UCSProject, which contains many string and List fields, i need to pass an instance of this class to the background worker, since the class is a bit heavy, i would like to reduce the number of duplicate instances by using the global variable directly, instead of passing it as an argument to the background worker.

To make it short, I just want to know is it safe to access global variables from a background worker thread in C#


回答1:


It is safe unless until both your threads(background & normal) not modifying the object.

If you want your object to be modified by each other, use Lock




回答2:


By your question I suspect that you do not understand how variables to classes work. You do not need a global variable to only have one copy of your object. All variables will point on exactly the same object unless you Clone it or create a new one with the old one as prototype.

A global variable will in other words change nothing unless you explicitly create new copies as described in the previous paragraph.

I do also wonder how heavy your class can be if you think that the performance would be hurt by creating copies of it? How many mb do it weight?

Update

This article series describes in great detail what the heap and stack is: http://www.c-sharpcorner.com/uploadfile/rmcochran/csharp_memory01122006130034pm/csharp_memory.aspx




回答3:


It is safe, but you have to synchronize access to the variables, e.g. by using the lock statement.

See "lock Statement" in the MSDN library.




回答4:


No, it is not, unless you're locking it with lock(object) { } whenever you use any of its data fields.




回答5:


If you're not modifying any of the strings or variables then you don't need to lock.

I'd also consider making this a static class if the data is shared across the whole application -- then you won't need to pass an instance.

If you need modify or update the data -- use Lock.




回答6:


You may also use [ThreadStatic]. The value of the variable will be unique for each thread. See MSDN for how to use it.



来源:https://stackoverflow.com/questions/4517038/is-it-safe-to-use-c-sharp-global-variables-in-a-background-worker-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!