Created
July 3, 2013 10:57
-
-
Save tugberkugurlu/5917020 to your computer and use it in GitHub Desktop.
Using SemaphoreSlim for async locking scenarios.
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
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