简体   繁体   中英

Multiple threads accessing same instance

ObservableCollection<MyClass> collection = new ObservableCollection<MyClass>();
public MainWindow()
{
    InitializeComponent();
    collection.Add(new MyClass() { Name = "Vikram" });
    collection.Add(new MyClass() { Name = "Test" });          

    CallingTaskDelay();          
    MyClass class1 = collection[0];
    lock (class1)
    {
        txtName.Text = class1.Name;
    }
}

private Task TaskDelayMethod()
{           
    return Task.Run(() => ChangeItem());
}

private async void CallingTaskDelay()
{
    await TaskDelayMethod();
}

private void ChangeItem()
{
    MyClass myclass = collection[0];
    lock (myclass)
    {
        myclass.Name = "anup";
        Thread.Sleep(5000);
    }
}

While I am changing the content of the instance of the myclass in ChangeItem() method. I want to prevent access of the same instance in the MainWindow() method which I am doing as below -

lock (class1)
{
     txtName.Text = class1.Name;
}

How it can be accomplished. Mine is not working.

Usually it is better to have a private object to use as a lock, but what you are doing should work as long as MyClass is a reference type. I think the code in your constructor executes before ChangeItem starts and hence you are not seeing any contention. try putting a Thread.Sleep(1000) after CallingTaskDelay() .

I guess you have a "Race condition". ChangeItem is probably not called yet when you acquire lock (class1) in constructor. Otherwise your code should work as expected.

You can check it by adding some sleep.

CallingTaskDelay();
Thread.Sleep(100);//For debugging, just give some time for  `CallingTaskDelay` to call `ChangeItem`
MyClass class1 = collection[0];
lock (class1)
{
    txtName.Text = class1.Name;
}

Are you expecting the ChangeItem() method to be run before the Constructor completes? Using the async keyword instructs the compiler to wait until it has nothing else to do before starting it. In the given scenario the ChangeItem() method will always be called After the Constructor completes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM