Make Synchronization Automatic
Use the [Synchronization] context attribute to provide automatic thread synchronization to a class.
by Juval Lowy
VSLive! SF, Day 2, February 13, 2002 When adding the [Synchronization] attribute, .NET automatically ensures that only one thread at a time can access the object. .NET automatically associates a synchronization lock with the object, locking it before every method call and unlocking it (to be used by other threads) when the method returns. This is a huge productivity gain, because thread synchronization and concurrency management are among the most common development pitfalls. There is a lot more to this attribute than mere synchronization, including strategies for sharing the lock with other objects, even classes developed by other vendors. This short demo walks you though the steps required to use the attribute in a simple scenario.
Add Synchronization Support
Open the AutoSynch demo. It contains a skeletal Windows Forms client and a simple class that acts as a counter. The class provides a public property of type int to access the counter, but it stores the counter internally as a string. The class can't accept calls by multiple threads at the same time, because that might corrupt its state. Open the MyClass.cs file and add the bolded code:
[Synchronization]
public class MyClass :
ContextBoundObject
{
protected string m_CountingString;
public int Counter
{
set
{
m_CountingString = "";
m_CountingString = value.ToString();
}
get
{
return
Convert.ToInt32(m_CountingString);
}
}
public MyClass()
{
m_CountingString = "0";
}
}
The class is now thread-safe.
The client displays the value of the counter in the m_CounterLabel label control (see the red label in Figure 1). The client will create two worker threadsone to increment the counter, and one to read the counter and update the form. The client caches as a member variable an instance of MyClass to store the counter:
public class SyncDemoForm : Form
{
private Button CreateThreads;
private Label m_CounterLabel;
protected MyClass m_MyClass;
public SyncDemoForm()
{
InitializeComponent();
m_MyClass = new MyClass();
m_CounterLabel.Text =
m_MyClass.Counter.ToString();
}
//rest of the class definition
Back to top
|