I looked at the section on memory barriers as described at http://www.albahari.com/threading/part4.aspx
and tried to make the async / await version of the example presented in the section “Do we really need locks and barriers?”:
public class Program
{
static void Main(string[] args)
{
TestAsync();
Console.ReadKey(true);
}
private static async void TestAsync()
{
bool complete = false;
Func<Task> testFunc = async () =>
{
await Task.Delay(1000);
bool toggle = false;
while (!complete) toggle = !toggle;
};
var task = testFunc();
Thread.Sleep(2000);
complete = true;
await task;
Console.WriteLine("Done");
}
}
When launched in the release mode without debugging, the program will never exit according to the original example of the thread on which it is based.
However, I was impressed with async / await because of the way the context was saved, this would prevent such problems. Or are all thread safety rules still applicable when using async / wait?