| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Threading; |
| | | 6 | | using System.Threading.Tasks; |
| | | 7 | | using CoreWCF; |
| | | 8 | | using CoreWCF.Runtime; |
| | | 9 | | |
| | | 10 | | namespace CoreWCF.Channels |
| | | 11 | | { |
| | | 12 | | internal class SynchronizedMessageSource |
| | | 13 | | { |
| | | 14 | | private readonly IMessageSource _source; |
| | | 15 | | private readonly SemaphoreSlim _sourceLock; |
| | | 16 | | |
| | 11 | 17 | | public SynchronizedMessageSource(IMessageSource source) |
| | | 18 | | { |
| | 11 | 19 | | _source = source; |
| | 11 | 20 | | _sourceLock = new SemaphoreSlim(1); |
| | 11 | 21 | | } |
| | | 22 | | |
| | | 23 | | public async Task<bool> WaitForMessageAsync(CancellationToken token) |
| | | 24 | | { |
| | 0 | 25 | | bool lockAcquired = false; |
| | | 26 | | try |
| | | 27 | | { |
| | 0 | 28 | | await _sourceLock.WaitAsync(token); |
| | 0 | 29 | | lockAcquired = true; |
| | 0 | 30 | | return await _source.WaitForMessageAsync(token); |
| | | 31 | | } |
| | 0 | 32 | | catch (OperationCanceledException) |
| | | 33 | | { |
| | | 34 | | // TODO: Fix the timeout value reported |
| | 0 | 35 | | throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( |
| | 0 | 36 | | SR.Format(SR.WaitForMessageTimedOut, TimeSpan.Zero), |
| | 0 | 37 | | TimeoutHelper.CreateEnterTimedOutException(TimeSpan.Zero))); |
| | | 38 | | } |
| | | 39 | | finally |
| | | 40 | | { |
| | 0 | 41 | | if (lockAcquired) |
| | | 42 | | { |
| | 0 | 43 | | _sourceLock.Release(); |
| | | 44 | | } |
| | | 45 | | } |
| | 0 | 46 | | } |
| | | 47 | | |
| | | 48 | | public async Task<Message> ReceiveAsync(CancellationToken token) |
| | | 49 | | { |
| | 26 | 50 | | bool lockAcquired = false; |
| | | 51 | | try |
| | | 52 | | { |
| | 26 | 53 | | await _sourceLock.WaitAsync(token); |
| | 26 | 54 | | lockAcquired = true; |
| | 26 | 55 | | return await _source.ReceiveAsync(token); |
| | | 56 | | } |
| | 0 | 57 | | catch (OperationCanceledException) |
| | | 58 | | { |
| | | 59 | | // TODO: Fix the timeout value reported |
| | 0 | 60 | | throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( |
| | 0 | 61 | | SR.Format(SR.ReceiveTimedOut2, TimeSpan.Zero), |
| | 0 | 62 | | TimeoutHelper.CreateEnterTimedOutException(TimeSpan.Zero))); |
| | | 63 | | } |
| | | 64 | | finally |
| | | 65 | | { |
| | 26 | 66 | | if (lockAcquired) |
| | | 67 | | { |
| | 26 | 68 | | _sourceLock.Release(); |
| | | 69 | | } |
| | | 70 | | } |
| | 26 | 71 | | } |
| | | 72 | | } |
| | | 73 | | } |