3

我目前编写 C# WPF 应用程序。我需要同步访问以从三个线程读取/写入变量。该变量被声明为应用程序主窗口类的成员。所以我通过以下方式声明它:

public partial class MainWindow : Window
{
    . . . . .
    #region Fields
    /// <summary>
    /// The variable myVar to synchronous access for read/write. 
    /// </summary>
    private static Double myVar;
    #endregion
    . . . . .
}

我可以通过以下方式提供对它的同步访问吗:

1)将同步对象定义为MainWindow类的成员

public partial class MainWindow : Window
{
    . . . . .
    #region Fields
    /// <summary>
    /// This object is controlling the synchronous access for read/write to myVar. 
    /// </summary>
    private static Object syncObj;
    #endregion
    . . . . .
}

2) 在 MainWindow 类中定义下一个属性

public partial class MainWindow : Window
{
    . . . . .
    #region Properties
    /// <summary>
    /// This property supports synchronous access to myVar for read/write. 
    /// </summary>
    public static Double MyVar
    {
        lock(syncObj)
        {
            get{ return myVar; }
            set{ if(myVar != value) myVar = value; }
        }
    } 
    #endregion
    . . . . .
}

这个属性会以正确的方式工作吗?它会确保对 myVar 变量进行读/写的同步访问的确定方法吗?我不想使用 volatile 或方法作为 Thread.VolatileRead 和 Thread.VolatileWrite,因为很多人说锁操作符工作得更好并且允许编译器优化代码。

4

3 回答 3

1

这似乎绝对没问题,只要主窗口不引用私有变量本身,而是引用属性。

From lock 语句(C# 参考)

lock 关键字通过获取给定对象的互斥锁、执行语句然后释放锁来将语句块标记为临界区。

lock 关键字确保一个线程不进入代码的临界区,而另一个线程在临界区。如果另一个线程试图输入一个锁定的代码,它将等待、阻塞,直到对象被释放。

另一个有趣的选择可能是ReaderWriterLockSlim 类

表示用于管理对资源的访问的锁,允许多个线程进行读取或独占访问进行写入

于 2012-09-28T05:54:09.913 回答
0

作为 StackOverflow 用户之一,我认为您的方法没有任何问题。就我个人而言,我还建议您看一下 ReaderWriterLockSlim 类,因为相对于代码执行期间的同步过程,它似乎真的很有趣。只要遵守这些规则

lock (this) is a problem if the instance can be accessed publicly.

lock (typeof (MyType)) is a problem if MyType is publicly accessible.

lock("myLock") is a problem because any other code in the process using the same string, will share the same lock.
于 2012-09-28T09:54:49.497 回答
0

Interlocked.CompareExchange您的方式会奏效,但您可以使用以下方法 获得更好的性能:http: //msdn.microsoft.com/en-us/library/cd0811yf.aspx

于 2012-09-28T09:58:18.103 回答