Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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#

like image 790
Vamsi Avatar asked Dec 21 '22 19:12

Vamsi


2 Answers

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

like image 64
RameshVel Avatar answered Feb 07 '23 13:02

RameshVel


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

like image 24
jgauffin Avatar answered Feb 07 '23 11:02

jgauffin