0

我相信我已经在这里成功实施了“自旋锁”,但我想研究这样的最佳实践。

我应该使用互锁类吗?如果是这样,哪种方法适合布尔值类型?否则,实现此目的的正确方法是什么(如果我的方法还不是)?

// This is a class to encapsulate a bool value that can be used
// as a signal from one thread to another.
public class Condition
{
    private object locker = new object();
    private bool isDone;

    public void Wait()
    {
        while (true) if (!this.Done) Thread.Sleep(100); else break;
    }

    public void Set()
    {
        this.Done = true;
    }

    private bool Done
    {
        get { lock (this.locker) { return this.isDone; } }
        set { lock (this.locker) { this.isDone = value; } }
    }
}

// This is an extension to a WSDL generated web service.
// The idea is to login to the web service as part of instance construction.
public partial class SforceService
{
    private Condition done = new Condition();

    public SforceService(string login, string password)
        : this()
    {
        this.loginCompleted += new loginCompletedEventHandler(SforceService_loginCompleted);
        this.loginAsync(login, password);
        this.done.Wait();
    }

    void SforceService_loginCompleted(object sender, loginCompletedEventArgs e)
    {
        var loginResult = e.Result;
        this.SessionHeaderValue = new SessionHeader();
        this.Url = loginResult.serverUrl;
        this.SessionHeaderValue.sessionId = loginResult.sessionId;
        this.done.Set();
    }
}
4

1 回答 1

1

我了解您正在尝试重新实现ManualResetEvent.

看一下 Set() 和 WaitOne() 方法,它们可能是您正在寻找的。

于 2012-04-14T05:02:30.477 回答