Created
February 17, 2022 09:39
-
-
Save mrpmorris/3fdfb413aa0dc276c0a7a5d81ab2b5aa to your computer and use it in GitHub Desktop.
Example of how to avoid multiple-thread access to DbContext in Blazor-Server
This file contains 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
Instead of this | |
return Db.Users.FirstOrDefaultAsync(x => x.EmailAddress == emailAddress); | |
do this | |
return Db.InvokeAsync(() => ...the query above...); | |
// Add the following methods to your DbContext | |
private SemaphoreSlim Semaphore { get; } = new SemaphoreSlim(1); | |
public TResult Invoke<TResult>(Func<TResult> action) | |
{ | |
Semaphore.Wait(); | |
try | |
{ | |
return action(); | |
} | |
finally | |
{ | |
Semaphore.Release(); | |
} | |
} | |
public async Task<TResult> InvokeAsync<TResult>(Func<Task<TResult>> action) | |
{ | |
await Semaphore.WaitAsync(); | |
try | |
{ | |
return await action(); | |
} | |
finally | |
{ | |
Semaphore.Release(); | |
} | |
} | |
public Task InvokeAsync(Func<Task> action) => | |
InvokeAsync<object>(async () => | |
{ | |
await action(); | |
return null; | |
}); | |
public void InvokeAsync(Action action) => | |
InvokeAsync(() => | |
{ | |
action(); | |
return Task.CompletedTask; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment