To synchronize your code, use a lock statement as we did previously. You can also reference the System.Runtime.CompilerServices namespace in your projects. Then, you can add the [MethodImpl(MethodImplOptions.Synchronized)] annotation to methods and properties.
Here is an example of the [MethodImpl(MethodImplOptions.Synchronized)] annotation applied to a method:
[MethodImpl(MethodImplOptions.Synchronized)]
public static void ThisIsASynchronisedMethod()
{
Console.WriteLine("Synchronised method called.");
}
Here is an example of using [MethodImpl(MethodImplOptions.Synchronized)] with a property:
private int i;
public int SomeProperty
{
[MethodImpl(MethodImplOptions.Synchronized)]
get { return i; }
[MethodImpl(MethodImplOptions.Synchronized)]
set { i = value; }
}
As you can see, it is easy to encounter a deadlock or a race condition, but it...