I want to know a good idea to Rewrite my class with Lambda + delegate + Func/Action.
in my code, there is lot of Lock wrapper ( to save a Sqlite model ).
using System.Threading;
using System.Threading.Tasks;
....
private SemaphoreSlim AsyncLock = new SemaphoreSlim(1);
....
private async Task LockWork1(SqliteModel model)
{
await AsyncLock.WaitAsync();
try { await Work1(model); }
finally { AsyncLock.Release(); }
}
private async Task LockWork2(SqliteModel model)
{
await AsyncLock.WaitAsync();
try{await Work2(model);}
finally{AsyncLock.Release();}
}
private async Task Work1(SqliteModel model){var a=model; await Task.Delay(1000);}
private async Task Work2(SqliteModel model){var a=model; await Task.Delay(2000);}
I want to make a Wrapper method to use lock. Here is my image.
await LockWrapper( Work1( modelInstance ) );
Func, Action() ? How to write it ??
Well you won't be able to do it quite like that, but you could write:
await LockWrapper(() => Work1(modelInstance));
and write LockWrapper
as:
private async Task LockWrapper(Func<Task> taskProvider)
{
await AsyncLock.WaitAsync();
try
{
await taskProvider();
}
finally
{
AsyncLock.Release();
}
}
The idea is that what you pass in is "the operation you need to perform" - you invoke that operation (taskProvider()
) and then wait for it to complete before unlocking.
Whether that's a good idea or not is a different matter though - I don't know what your AsyncLock
is, or whether it assumes that WaitAsync
and Release
will be called on the same thread. If it assumes that, this code could still be okay if LockWrapper
is called in a single-thread synchronization context, but it feels a bit fragile to me.
See more on this question at Stackoverflow