protected async Task <TResponse> WriteMessageWithResponseAsync <TRequest, TResponse>(int methodId, TRequest message) { ThrowIfDisposed(); var mid = Interlocked.Increment(ref messageId); var tcs = new TaskCompletionSourceEx <TResponse>(); // use Ex responseFutures[mid] = (object)tcs; byte[] BuildMessage() { using (var buffer = ArrayPoolBufferWriter.RentThreadStaticWriter()) { var writer = new MessagePackWriter(buffer); writer.WriteArrayHeader(3); writer.Write(mid); writer.Write(methodId); MessagePackSerializer.Serialize(ref writer, message, serializerOptions); writer.Flush(); return(buffer.WrittenSpan.ToArray()); } } var v = BuildMessage(); using (await asyncLock.LockAsync().ConfigureAwait(false)) { await connection.RawStreamingCall.RequestStream.WriteAsync(v).ConfigureAwait(false); } return(await tcs.Task); // wait until server return response(or error). if connection was closed, throws cancellation from DisposeAsyncCore. }
public RSessionEvaluation(IReadOnlyList <IRContext> contexts, IRExpressionEvaluator evaluator, CancellationToken hostCancellationToken) { Contexts = contexts; _evaluator = evaluator; _tcs = new TaskCompletionSourceEx <object>(); _hostCancellationRegistration = hostCancellationToken.Register(() => _tcs.TrySetCanceled(new RHostDisconnectedException())); }
public static Task WhenAllCancelOnFailure(IEnumerable <Func <CancellationToken, Task> > functions, CancellationToken cancellationToken) { var functionsArray = functions.AsArray(); if (functionsArray.Length == 0) { return(Task.CompletedTask); } if (functionsArray.Length == 1) { return(functionsArray[0](cancellationToken)); } CancellationTokenSource cts; try { cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); } catch (Exception) when(cancellationToken.IsCancellationRequested) { return(Task.FromCanceled(cancellationToken)); } var tcs = new TaskCompletionSourceEx <bool>(); var state = new WhenAllCancelOnFailureContinuationState(functionsArray.Length, tcs, cts); foreach (var function in functionsArray) { Task.Run(() => function(cts.Token) .ContinueWith(WhenAllCancelOnFailureContinuation, state, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default)); } return(tcs.Task); }
public RSessionRequestSource(bool isVisible, CancellationToken ct) { _createRequestTcs = new TaskCompletionSourceEx<IRSessionInteraction>(); _responseTcs = new TaskCompletionSourceEx<object>(); _cancellationTokenRegistration = ct.Register(() => _createRequestTcs.TrySetCanceled(cancellationToken:ct)); IsVisible = isVisible; }
public RSessionRequestSource(bool isVisible, CancellationToken ct) { _createRequestTcs = new TaskCompletionSourceEx <IRSessionInteraction>(); _responseTcs = new TaskCompletionSourceEx <object>(); ct.Register(() => _createRequestTcs.TrySetCanceled(cancellationToken: ct)); IsVisible = isVisible; }
public void TrySetException() { var tcs = new TaskCompletionSourceEx<int>(); var count = 0; ParallelTools.Invoke(8, i => { var isSet = tcs.TrySetException(new Exception()); if (isSet) { Interlocked.Increment(ref count); } }); count.Should().Be(1); }
public static Task WhenAllCancelOnFailure(IEnumerable <Func <CancellationToken, Task> > functions, CancellationToken cancellationToken) { var functionsList = functions.ToList(); var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var tcs = new TaskCompletionSourceEx <bool>(); var state = new WhenAllCancelOnFailureContinuationState(functionsList.Count, tcs, cts); Parallel.ForEach(functionsList, function => { var task = function(cts.Token); task.ContinueWith(WhenAllCancelOnFailureContinuation, state, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); }); return(tcs.Task); }
private static async Task RunHost(RHost host, TaskCompletionSourceEx <object> hostStartedTcs, CancellationToken initializationCt) { try { await host.Run(initializationCt); } catch (OperationCanceledException oce) { hostStartedTcs.TrySetCanceled(oce); } catch (MessageTransportException mte) { hostStartedTcs.TrySetCanceled(new RHostDisconnectedException(string.Empty, mte)); } catch (Exception ex) { hostStartedTcs.TrySetException(ex); } finally { // RHost.Run shouldn't be completed before `IRCallback.Connected` is called hostStartedTcs.TrySetCanceled(new RHostDisconnectedException(Resources.Error_UnknownError)); } }
public void TrySetException() { var tcs = new TaskCompletionSourceEx <int>(); var count = 0; ParallelTools.Invoke(8, i => { var isSet = tcs.TrySetException(new Exception()); if (isSet) { Interlocked.Increment(ref count); } }); count.Should().Be(1); }
public RSession(int id, IBrokerClient brokerClient, Action onDispose) { Id = id; BrokerClient = brokerClient; _onDispose = onDispose; _disposeToken = DisposeToken.Create <RSession>(); _disableMutatingOnReadConsole = new CountdownDisposable(() => { if (!_delayedMutatedOnReadConsole) { return; } _delayedMutatedOnReadConsole = false; Task.Run(() => Mutated?.Invoke(this, EventArgs.Empty)); }); _initializationLock = new BinaryAsyncLock(); _initializationTcs = new TaskCompletionSourceEx <object>(); _afterHostStartedTask = TaskUtilities.CreateCanceled(new RHostDisconnectedException()); }
protected async Task <TResponse> WriteMessageWithResponseAsync <TRequest, TResponse>(int methodId, TRequest message) { ThrowIfDisposed(); var mid = Interlocked.Increment(ref messageId); var tcs = new TaskCompletionSourceEx <TResponse>(); // use Ex responseFutures[mid] = (object)tcs; #if NON_UNITY var rent = System.Buffers.ArrayPool <byte> .Shared.Rent(ushort.MaxValue); #else var rent = MessagePack.Internal.BufferPool.Default.Rent(); #endif var buffer = rent; byte[] v; try { var offset = 0; offset += MessagePackBinary.WriteArrayHeader(ref buffer, offset, 3); offset += MessagePackBinary.WriteInt32(ref buffer, offset, mid); offset += MessagePackBinary.WriteInt32(ref buffer, offset, methodId); offset += LZ4MessagePackSerializer.SerializeToBlock(ref buffer, offset, message, resolver); v = MessagePackBinary.FastCloneWithResize(buffer, offset); } finally { #if NON_UNITY System.Buffers.ArrayPool <byte> .Shared.Return(rent); #else MessagePack.Internal.BufferPool.Default.Return(rent); #endif } using (await asyncLock.LockAsync().ConfigureAwait(false)) { await connection.RawStreamingCall.RequestStream.WriteAsync(v).ConfigureAwait(false); } return(await tcs.Task); // wait until server return response(or error). if connection was closed, throws cancellation from DisposeAsyncCore. }
public RSession(int id, string name, IBrokerClient brokerClient, IExclusiveReaderLock initializationLock, Action onDispose) { Id = id; Name = name; BrokerClient = brokerClient; _onDispose = onDispose; _disposeToken = DisposeToken.Create <RSession>(); _disableMutatingOnReadConsole = new CountdownDisposable(() => { if (!_delayedMutatedOnReadConsole) { return; } _delayedMutatedOnReadConsole = false; Task.Run(() => Mutated?.Invoke(this, EventArgs.Empty)); }); _initializationLock = initializationLock; _stopHostLock = new BinaryAsyncLock(true); _hostStartedTcs = new TaskCompletionSourceEx <object>(); _startupInfo = new RHostStartupInfo(); }
public ExecuteInQueueAsyncItem(Func <CancellationToken, Task> handler) { _handler = handler; _tcs = new TaskCompletionSourceEx <T>(); }
public WhenAllCancelOnFailureContinuationState(int count, TaskCompletionSourceEx <bool> taskCompletionSource, CancellationTokenSource cancellationTokenSource) { Count = count; TaskCompletionSource = taskCompletionSource; CancellationTokenSource = cancellationTokenSource; }
public Task AsynchronousInvoke( IRequestChannel channel, TChannelBufferInputTransport inputTransport, TChannelBufferOutputTransport outputTransport, TProtocol inputProtocol, TProtocol outputProtocol, int sequenceId, ClientContextChain contextChain, Object[] args) { //Mark: 微软没有提供 TaskCompletionSource 的非泛型类型,只能使用动态类型处理。 TaskCompletionSourceEx future; if (_successCodec.Type != ThriftType.Void) { future = new TaskCompletionSourceEx(_successCodec.Type.CSharpType); } else { future = new TaskCompletionSourceEx(typeof(Object)); } var requestContext = RequestContexts.GetCurrentContext(); contextChain.PreWrite(args); outputTransport.ResetOutputBuffer(); WriteArguments(outputProtocol, sequenceId, args); IByteBuffer requestBuffer = outputTransport.OutputBuffer.Copy(); contextChain.PostWrite(args); requestBuffer.Retain(); channel.SendAsynchronousRequest(requestBuffer, false, new RequestListener( onRequestSent: reqs => { reqs.Release(); if (this._oneway) { try { ForceDoneChain(contextChain); future.TrySetResult(null); } catch (Exception e) { ForceDoneChain(contextChain); future.TrySetException(e); } } }, onResponseReceive: message => { IRequestContext oldRequestContext = RequestContexts.GetCurrentContext(); RequestContexts.SetCurrentContext(requestContext); try { contextChain.PreRead(); inputTransport.SetInputBuffer(message); WaitForResponse(inputProtocol, sequenceId); Object results = ReadResponse(inputProtocol); contextChain.PostRead(results); ForceDoneChain(contextChain); future.TrySetResult(results); } catch (Exception e) { var wrapException = ThriftClientManager.WrapTException(e); contextChain.PostReadException(e); ForceDoneChain(contextChain); future.TrySetException(wrapException); } finally { RequestContexts.SetCurrentContext(oldRequestContext); } }, onChannelError: e => { if (requestBuffer.ReferenceCount > 0) { requestBuffer.Release(); } IRequestContext oldRequestContext = RequestContexts.GetCurrentContext(); RequestContexts.SetCurrentContext(requestContext); try { contextChain.PreReadException(e); ForceDoneChain(contextChain); var wrappedException = ThriftClientManager.WrapTException(e); future.TrySetException(wrappedException); } finally { RequestContexts.SetCurrentContext(oldRequestContext); } } )); return(future.Task); }
public RSessionEvaluationSource(CancellationToken clientCancellationToken) { _tcs = new TaskCompletionSourceEx <IRSessionEvaluation>(); clientCancellationToken.Register(() => _tcs.TrySetCanceled(cancellationToken: clientCancellationToken), false); }
public static void SetCompletionResultTo <T>(this Task <T> task, TaskCompletionSourceEx <T> tcs) => task.ContinueWith(SetCompletionResultToContinuation, tcs, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);