-3

I have written a small method. It basically calls to a service (not web service) to set a lock attribute. It does work, but I am interested in improving it. Should I really be running this in a new thread?

I have this running inside a do..while and I have no thread.sleep between calls.

I am using the stopwatch to record when its actually more than 20 seconds and I exit anyway as no lock was able to be set.

public bool ObtainLock(Uri lockUri)
{
    bool lockResult = false;

    var sw = new Stopwatch();
    sw.Start();
    do
    {
        lockResult = myService.SetLockBit(lockUri);
    }
    while (!lockResult || sw.ElapsedMilliseconds >= 20000);

    sw.Stop();

    return lockResult;
}

It just seems to me it could be improved, and the threading worries me. A note, the myservice isn't a web service, its just another method on a class so I can use Task<..> here.

And the stopwatch I am using, is that an acceptable way of implementing a timeout?

4

2 回答 2

1

I would if this is your UI thread. Perhaps a Timer would be better? Perhaps you should use a SpinLock?

于 2013-09-13T15:56:45.473 回答
0

If this can be improved or not depends on what's going on. Should you spawn a new thread for this? If you need the current thread for something else (e.g. UI updates) while you're waiting to SetLockBit, then yes. If you don't need the current thread to do anything, then this is fine.

The stopwatch is fine. However, if you know that locks are likely to be held for seconds at a time, you may want to wait a bit longer before calling SetLockBit again. If you know that they are released very quickly, but there's a lot of contention, then you may want to keep this.

于 2013-09-13T17:38:45.853 回答