我目前编写 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,因为很多人说锁操作符工作得更好并且允许编译器优化代码。