Vamsi
Vamsi

Reputation: 4253

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#

Upvotes: 4

Views: 20661

Answers (6)

cumhuryalcin
cumhuryalcin

Reputation: 13

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

Upvotes: 0

Tim Barrass
Tim Barrass

Reputation: 4939

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.

Upvotes: 1

jgauffin
jgauffin

Reputation: 101140

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

Upvotes: 3

Andrei Sosnin
Andrei Sosnin

Reputation: 730

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

Upvotes: 1

RameshVel
RameshVel

Reputation: 65867

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

Upvotes: 5

Uwe Keim
Uwe Keim

Reputation: 40736

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.

Upvotes: 1

Related Questions