Domanda

Here is my class:

public class Server
{
    public string Name{get;set;}
    public void DoTheJob()
    {
        //MoreCode
    }
}

I have created a new instance of Server and I want to make the instance inaccessible while DoTheJob() is running.

Can I do something like this?

DoTheJob()
{
    lock(this)
    {
        //logic
    }
}
È stato utile?

Soluzione

Yes you can, but you should not lock on this to avoid deadlocks. Use something like:

public class Server
{
    private object lockObject = new object();

    public string Name { get; set; }
    public void DoTheJob()
    {
        lock(lockObject)
        {
            //MoreCode
        }
    }
}

If you also want to avoid the reading of Name you would need to implement a getter and setter which also use the same lock.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top