Skip to content

Instantly share code, notes, and snippets.

@tugberkugurlu
Created July 3, 2013 10:57
Show Gist options
  • Save tugberkugurlu/5917020 to your computer and use it in GitHub Desktop.
Save tugberkugurlu/5917020 to your computer and use it in GitHub Desktop.
Using SemaphoreSlim for async locking scenarios.
private static readonly SemaphoreSlim __questionCloseLock = new SemaphoreSlim(initialCount: 1);
public async Task<OperationResult<QuestionCloseRecord>> CloseQuestionAsync(int questionId, QuestionCloseType closeType)
{
try
{
await __questionCloseLock.WaitAsync().ConfigureAwait(false);
Question question = await GetQuestionAsync(questionId).ConfigureAwait(false);
if (question == null || question.CloseRecord != null)
{
return new OperationResult<QuestionCloseRecord>(false);
}
question.CloseRecord = new QuestionCloseRecord
{
ClosedOn = DateTimeOffset.Now,
ClosedBy = closeType
};
_questionRepository.Edit(question);
int result = await _questionRepository.SaveAsync().ConfigureAwait(false);
return result > 0
? new OperationResult<QuestionCloseRecord>(true) { Entity = question.CloseRecord }
: new OperationResult<QuestionCloseRecord>(false);
}
finally
{
__questionCloseLock.Release();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment