Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Safe to alter a class variable from alternate threads?

Status
Not open for further replies.

steve4king

IS-IT--Management
Feb 6, 2007
154
0
0
US
I've got a simple application partially for work, partially to learn.

The program connects to a database, gathers a total record count, displays that count, then walks through each item, displaying the current record number as it goes.

All of the database queries happen on a background worker thread. The program works if I declare a few class level variables, and update those variables directly from the background worker thread method. Then during the progress changed method I set the UI component to the class variable.

I've been reading a bit about thread-safety and I'm not sure whether this is a good idea or whether I need to be passing all of these variables explicitly from method to method rather than method to class to method.


I've probably made this very confusing, and if so I apologize hehe.

Thanks for any help!

 
With separate threads accessing a class-level variable I would lock the variable when accessing it.
Code:
public class Test
{
    private MyObject myVariable = new MyObject();

    private void DoSomething()
    {
        lock(myVariable)
        {
            myVariable.Foo = "Test";
            myVaiable.Bar();
        }
    }
}
 
Only one thread is altering the variable, the other is only reading and updating the UI. Is there still a reason to lock it?

Thanks
 
it's best to avoid cross threading when possible. from time to time it's necessary (IoC containers and Singletons usually involve a locking) but for the most part this shouldn't be too common. Another option is to create immutable objects. if an object needs to change you create a new instance of the object and set the new value. the original object remains unchanged. A common example is a Money or Point object.

if you are updating the UI then you must sync the background work to the main thread. You cannot update the UI from a background thread. I have an FAQ on UI thread synchronization. Link is in my signature below if you're interested.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top