Last active
August 24, 2019 21:57
-
-
Save kekyo/7c79b9964acf0f51a828d0ef908b37bc to your computer and use it in GitHub Desktop.
Awaiting on Monitor lock vs. AsyncEx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using Nito.AsyncEx; | |
namespace ConsoleApp4 | |
{ | |
public static class Program | |
{ | |
private static readonly object monitorLockTarget = new object(); | |
#if false | |
private static async Task InvalidAwaitingUsage() | |
{ | |
lock (monitorLockTarget) | |
{ | |
using (var fs = new FileStream("nyaruko.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 65536, true)) | |
{ | |
var tw = new StreamWriter(fs, Encoding.UTF8); | |
// error CS1996: Cannot await in the body of a lock statement | |
await tw.WriteLineAsync("She has a likely bar."); | |
await tw.FlushAsync(); | |
} | |
} | |
} | |
#endif | |
private static async Task DangerousForceAwaitingUsage() | |
{ | |
Monitor.Enter(monitorLockTarget); | |
try | |
{ | |
using (var fs = new FileStream("nyaruko.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 65536, true)) | |
{ | |
var tw = new StreamWriter(fs, Encoding.UTF8); | |
await tw.WriteLineAsync("She has a likely bar."); | |
await tw.FlushAsync(); | |
} | |
} | |
finally | |
{ | |
Monitor.Exit(monitorLockTarget); | |
} | |
} | |
private static readonly AsyncLock asyncLockTarget = new AsyncLock(); | |
private static async Task ValidAwaitingUsage() | |
{ | |
using (await asyncLockTarget.LockAsync()) | |
{ | |
using (var fs = new FileStream("nyaruko.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 65536, true)) | |
{ | |
var tw = new StreamWriter(fs, Encoding.UTF8); | |
// Can do it. | |
await tw.WriteLineAsync("She has a likely bar."); | |
await tw.FlushAsync(); | |
} | |
} | |
} | |
static async Task Main(string[] args) | |
{ | |
// System.Threading.SynchronizationLockException: 'Object synchronization method was called from an unsynchronized block of code.' | |
await DangerousForceAwaitingUsage(); | |
await ValidAwaitingUsage(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment