Question

i can not see the error, maybe someone can help me out here.

I have a custom lock using spinlock (it's a for school)

 public class Spinlock : Locker
{
    Boolean locked = false;
    private SpinLock spinLock = new SpinLock();

    public override void LockIt()
    {
        try
        {
            spinLock.Enter(ref locked);
        }
        finally
        {
            if(locked)
                spinLock.Exit();
        }
    }

    public override void UnlockIt()
    {
    }
}

 public abstract class Locker
{
    abstract public void LockIt();
    abstract public void UnlockIt();
}

The exception i get is the following:

System.ArgumentException was unhandled

Message=The tookLock argument must be set to false before calling this method.

Was it helpful?

Solution

Yes, this is not correct code. It will fail when a second thread also enters the lock and it is already held. The locked variable must be a local variable to ensure that it has thread affinity. Fix:

public override void LockIt()
{
    bool locked = false;
    try
    {
        spinLock.Enter(ref locked);
    }
    finally
    {
        if(locked)
            spinLock.Exit();
    }
}

Do note that the code otherwise makes no sense, there is no point in entering a lock and then immediately exit it again. I assume that's your real homework assignment.

OTHER TIPS

The code works fine for me. You must make sure before you enter the lock (spinLock.Enter) that locked is false. Otherwise you'll get this exception!

Seems that some other part of your code overwrites that variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top