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

Hi I am working on a simple desktop application, it has to handle some operations, such as loading a web page that can block the main thread, so I moved the code to a background worker.

My problem is that there is a heavy class called UCSProject that contains a lot of rows and List fields, I need to pass an instance of this class to a background worker, since the class is a bit heavy, I would like to reduce the number of duplicate instances using a global variable directly. instead of passing it as an argument to the desktop background.

To do this briefly, I just want to know whether it is safe to access global variables from a workflow in C #

+4
source share
6 answers

This is safe unless your threads (background and normal) do not modify the object.

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

+5
source

On your question, I suspect you don’t understand how variables work in classes. You do not need a global variable to have only one copy of your object. All variables will point to the same object, unless you Clone it or create a new one with the old prototype.

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

I also wonder how heavy your class can be if you think the performance will be damaged by making copies of it? How much mb is the weight?

Update

This series of articles details what the heap and the stack are: http://www.c-sharpcorner.com/uploadfile/rmcochran/csharp_memory01122006130034pm/csharp_memory.aspx

+3
source

It is safe, but you need to synchronize access to variables, for example. using the lock statement.

See " Blocking Statement " in the MSDN Library.

+1
source

No, this is not the case if you do not lock it with lock(object) { } whenever you use any of its data fields.

+1
source

If you do not change any of the lines or variables, you do not need to block.

I would also think about making this a static class, if the data is distributed throughout the application - then you will not need to pass an instance.

If you need to change or update data, use Lock .

+1
source

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

0
source

Source: https://habr.com/ru/post/1333156/


All Articles