Skip to content

Instantly share code, notes, and snippets.

@mrpmorris
Created February 17, 2022 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrpmorris/3fdfb413aa0dc276c0a7a5d81ab2b5aa to your computer and use it in GitHub Desktop.
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
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