I presently write C# WPF application. I'm in need of synchronous access for read/write to a variable from three threads. This variable is declared as the member of the application main window class. So I declared it in the following way:
public partial class MainWindow : Window
{
. . . . .
#region Fields
/// <summary>
/// The variable myVar to synchronous access for read/write.
/// </summary>
private static Double myVar;
#endregion
. . . . .
}
Can I provide the synchronous access to it in the following way:
1) Define the synchronization object as the member of MainWindow class
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) Define the next property in the MainWindow class
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
. . . . .
}
Will this property work in the right way? Will it ensure sure method of synchronous access for read/write to myVar variable? I don't want to use volatile or methods as Thread.VolatileRead and Thread.VolatileWrite because many people say that lock operator works better and allow to compiler to optimize code.