当前位置: 首页>>代码示例>>C#>>正文


C# CancellationTokenRegistration.Dispose方法代码示例

本文整理汇总了C#中System.Threading.CancellationTokenRegistration.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# CancellationTokenRegistration.Dispose方法的具体用法?C# CancellationTokenRegistration.Dispose怎么用?C# CancellationTokenRegistration.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Threading.CancellationTokenRegistration的用法示例。


在下文中一共展示了CancellationTokenRegistration.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: DefaultCancellationTokenRegistration

        public void DefaultCancellationTokenRegistration()
        {
            var registration = new CancellationTokenRegistration ();

            // shouldn't throw
            registration.Dispose ();
        }
开发者ID:mesheets,项目名称:Theraot-CF,代码行数:7,代码来源:CancellationTokenTests.cs

示例2: FromAsync

        // Similar to TaskFactory.FromAsync, except it supports cancellation using ICancellableAsyncResult.
        public static Task FromAsync(Func<AsyncCallback, object, ICancellableAsyncResult> beginMethod,
            Action<IAsyncResult> endMethod, CancellationToken cancellationToken)
        {
            TaskCompletionSource<object> source = new TaskCompletionSource<object>();

            CancellationTokenRegistration cancellationRegistration = new CancellationTokenRegistration();
            bool cancellationRegistrationDisposed = false;
            object cancellationRegistrationLock = new object();

            ICancellableAsyncResult result = beginMethod.Invoke((ar) =>
            {
                lock (cancellationRegistrationLock)
                {
                    cancellationRegistration.Dispose();
                    cancellationRegistrationDisposed = true;
                }

                try
                {
                    endMethod.Invoke(ar);
                    source.SetResult(null);
                }
                catch (OperationCanceledException)
                {
                    source.SetCanceled();
                }
                catch (Exception exception)
                {
                    source.SetException(exception);
                }
            }, null);

            lock (cancellationRegistrationLock)
            {
                if (!cancellationRegistrationDisposed)
                {
                    cancellationRegistration = cancellationToken.Register(result.Cancel);
                }
            }

            if (result.CompletedSynchronously)
            {
                System.Diagnostics.Debug.Assert(source.Task.IsCompleted);
            }

            return source.Task;
        }
开发者ID:rafaelmtz,项目名称:azure-webjobs-sdk,代码行数:48,代码来源:CancellableTaskFactory.cs

示例3: Delay

        public static Task Delay(int dueTimeMs, CancellationToken cancellationToken)
        {
            if (dueTimeMs < -1) throw new ArgumentOutOfRangeException("dueTimeMs", "Invalid due time");
            if (cancellationToken.IsCancellationRequested) return preCanceledTask;
            if (dueTimeMs == 0) return preCompletedTask;

            var tcs = new TaskCompletionSource<object>();
            var ctr = new CancellationTokenRegistration();
            var timer = new Timer(self =>
            {
                ctr.Dispose();
                ((Timer) self).Dispose();
                tcs.TrySetResult(null);
            });
            if (cancellationToken.CanBeCanceled)
                ctr = cancellationToken.Register(() =>
                {
                    timer.Dispose();
                    tcs.TrySetCanceled();
                });
            timer.Change(dueTimeMs, -1);
            return tcs.Task;
        }
开发者ID:nbouilhol,项目名称:bouilhol-lib,代码行数:23,代码来源:TaskEx.cs

示例4: WriteAsyncCore

        private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this, WebSocketValidate.GetTraceMsgForParameters(offset, count, cancellationToken));
            }

            CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();

            try
            {
                if (cancellationToken.CanBeCanceled)
                {
                    cancellationTokenRegistration = cancellationToken.Register(s_OnCancel, this, false);
                }

                if (!_inOpaqueMode)
                {
                    await _outputStream.WriteAsync(buffer, offset, count, cancellationToken).SuppressContextFlow();
                }
                else
                {
#if DEBUG
                    // When using fast path only one outstanding read is permitted. By switching into opaque mode
                    // via IWebSocketStream.SwitchToOpaqueMode (see more detailed comments in interface definition)
                    // caller takes responsibility for enforcing this constraint.
                    Debug.Assert(Interlocked.Increment(ref _outstandingOperations._writes) == 1,
                        "Only one outstanding write allowed at any given time.");
#endif
                    _writeTaskCompletionSource = new TaskCompletionSource<object>();
                    _writeEventArgs.BufferList = null;
                    _writeEventArgs.SetBuffer(buffer, offset, count);
                    if (WriteAsyncFast(_writeEventArgs))
                    {
                        await _writeTaskCompletionSource.Task.SuppressContextFlow();
                    }
                }
            }
            catch (Exception error)
            {
                if (s_CanHandleException(error))
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }

                throw;
            }
            finally
            {
                cancellationTokenRegistration.Dispose();

                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Exit(this);
                }
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:57,代码来源:WebSocketHttpListenerDuplexStream.cs

示例5: MultipleWriteAsyncCore

        private async Task MultipleWriteAsyncCore(IList<ArraySegment<byte>> sendBuffers, CancellationToken cancellationToken)
        {
            Debug.Assert(sendBuffers != null, "'sendBuffers' MUST NOT be NULL.");
            Debug.Assert(sendBuffers.Count == 2, "'sendBuffers.Count' MUST be '2' at this point.");

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this);
            }

            CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();

            try
            {
                if (cancellationToken.CanBeCanceled)
                {
                    cancellationTokenRegistration = cancellationToken.Register(s_OnCancel, this, false);
                }
#if DEBUG
                // When using fast path only one outstanding read is permitted. By switching into opaque mode
                // via IWebSocketStream.SwitchToOpaqueMode (see more detailed comments in interface definition)
                // caller takes responsibility for enforcing this constraint.
                Debug.Assert(Interlocked.Increment(ref _outstandingOperations._writes) == 1,
                    "Only one outstanding write allowed at any given time.");
#endif
                _writeTaskCompletionSource = new TaskCompletionSource<object>();
                _writeEventArgs.SetBuffer(null, 0, 0);
                _writeEventArgs.BufferList = sendBuffers;
                if (WriteAsyncFast(_writeEventArgs))
                {
                    await _writeTaskCompletionSource.Task.SuppressContextFlow();
                }
            }
            catch (Exception error)
            {
                if (s_CanHandleException(error))
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }

                throw;
            }
            finally
            {
                cancellationTokenRegistration.Dispose();

                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Exit(this);
                }
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:52,代码来源:WebSocketHttpListenerDuplexStream.cs

示例6: EnsureReadAsync

        private async Task<byte[]> EnsureReadAsync(int readSize, CancellationToken token)
        {
            var cancelTaskToken = new CancellationTokenRegistration();
            try
            {
                await _singleReaderSemaphore.WaitAsync(token);

                var buffer = new byte[readSize];
                var length = 0;
                var offset = 0;

                while (length < readSize)
                {
                    readSize = readSize - length;
                    var client = await GetClientAsync();

                    // Read asynchronously to the receive buffer
                    length = await client.GetStream()
                        .ReadAsync(buffer, offset, readSize, token)
                        .WithCancellation(token);
                    if (length <= 0)
                    {
                        // Attempt to trigger a reconnection and throw an error
                        this.TriggerReconnection();
                        throw new ServerDisconnectedException(string.Format("Lost connection to server: {0}", _endpoint));
                    }

                    // Increase the offset in the buffer
                    offset += length;
                }

                return buffer;
            }
            catch
            {
                if (_disposeToken.IsCancellationRequested)
                    throw new ObjectDisposedException("Object is disposing.");
                //TODO add exception test here to see if an exception made us lose a connection Issue #17
                throw;
            }
            finally
            {
                cancelTaskToken.Dispose();
                _singleReaderSemaphore.Release();
            }
        }
开发者ID:thetechi,项目名称:misakai-kafka,代码行数:46,代码来源:KafkaTcpSocket.cs

示例7: ExecuteDbDataReaderAsync

        protected virtual Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) {
            if (cancellationToken.IsCancellationRequested) {
                return ADP.CreatedTaskWithCancellation<DbDataReader>();
            }
            else {
                CancellationTokenRegistration registration = new CancellationTokenRegistration();
                if (cancellationToken.CanBeCanceled) {
                    registration = cancellationToken.Register(CancelIgnoreFailure);
                }

                try {
                    return Task.FromResult<DbDataReader>(ExecuteReader(behavior));
                }
                catch (Exception e) {
                    registration.Dispose();
                    return ADP.CreatedTaskWithException<DbDataReader>(e);
                }
            }
        }
开发者ID:krytht,项目名称:DotNetReferenceSource,代码行数:19,代码来源:DBCommand.cs

示例8: ReEntrantRegistrationTest

		public void ReEntrantRegistrationTest ()
		{
			bool unregister = false;
			bool register = false;
			var source = new CancellationTokenSource ();
			var token = source.Token;

			var reg = new CancellationTokenRegistration ();
			Console.WriteLine ("Test1");
			token.Register (() => reg.Dispose ());
			reg = token.Register (() => unregister = true);
			token.Register (() => { Console.WriteLine ("Gnyah"); token.Register (() => register = true); });
			source.Cancel ();

			Assert.IsFalse (unregister);
			Assert.IsTrue (register);
		}
开发者ID:nicolas-raoul,项目名称:mono,代码行数:17,代码来源:CancellationTokenSourceTest.cs

示例9: ReadAsyncCore

        private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            if (WebSocketBase.LoggingEnabled)
            {
                Logging.Enter(Logging.WebSockets, this, Methods.ReadAsyncCore, 
                    WebSocketHelpers.GetTraceMsgForParameters(offset, count, cancellationToken));
            }

            CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();

            int bytesRead = 0;
            try
            {
                if (cancellationToken.CanBeCanceled)
                {
                    cancellationTokenRegistration = cancellationToken.Register(s_OnCancel, this, false);
                }

                if (!m_InOpaqueMode)
                {
                    bytesRead = await m_InputStream.ReadAsync(buffer, offset, count, cancellationToken).SuppressContextFlow<int>();
                }
                else
                {
#if DEBUG
                    // When using fast path only one outstanding read is permitted. By switching into opaque mode
                    // via IWebSocketStream.SwitchToOpaqueMode (see more detailed comments in interface definition)
                    // caller takes responsibility for enforcing this constraint.
                    Contract.Assert(Interlocked.Increment(ref m_OutstandingOperations.m_Reads) == 1,
                        "Only one outstanding read allowed at any given time.");
#endif
                    m_ReadTaskCompletionSource = new TaskCompletionSource<int>();
                    m_ReadEventArgs.SetBuffer(buffer, offset, count);
                    if (!ReadAsyncFast(m_ReadEventArgs))
                    {
                        if (m_ReadEventArgs.Exception != null)
                        {
                            throw m_ReadEventArgs.Exception;
                        }

                        bytesRead = m_ReadEventArgs.BytesTransferred;
                    }
                    else
                    {
                        bytesRead = await m_ReadTaskCompletionSource.Task.SuppressContextFlow<int>();
                    }
                }
            }
            catch (Exception error)
            {
                if (s_CanHandleException(error))
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }

                throw;
            }
            finally
            {
                cancellationTokenRegistration.Dispose();

                if (WebSocketBase.LoggingEnabled)
                {
                    Logging.Exit(Logging.WebSockets, this, Methods.ReadAsyncCore, bytesRead);
                }
            }

            return bytesRead;
        }
开发者ID:uQr,项目名称:referencesource,代码行数:69,代码来源:WebSocketHttpListenerDuplexStream.cs

示例10: CloseNetworkConnectionAsync

        public async Task CloseNetworkConnectionAsync(CancellationToken cancellationToken)
        {
            // need to yield here to make sure that we don't get any exception synchronously
            await Task.Yield();
            if (WebSocketBase.LoggingEnabled)
            {
                Logging.Enter(Logging.WebSockets, this, Methods.CloseNetworkConnectionAsync, string.Empty);
            }

            CancellationTokenSource reasonableTimeoutCancellationTokenSource = null;
            CancellationTokenSource linkedCancellationTokenSource = null;
            CancellationToken linkedCancellationToken = CancellationToken.None;

            CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();
            
            int bytesRead = 0;
            try
            {
                reasonableTimeoutCancellationTokenSource = 
                    new CancellationTokenSource(WebSocketHelpers.ClientTcpCloseTimeout);
                linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(
                    reasonableTimeoutCancellationTokenSource.Token,
                    cancellationToken);
                linkedCancellationToken = linkedCancellationTokenSource.Token;
                cancellationTokenRegistration = linkedCancellationToken.Register(s_OnCancel, this, false);

                WebSocketHelpers.ThrowIfConnectionAborted(m_ConnectStream.Connection, true);
                byte[] buffer = new byte[1];
                if (m_WebSocketConnection != null && m_InOpaqueMode)
                {
                    bytesRead = await m_WebSocketConnection.ReadAsyncCore(buffer, 0, 1, linkedCancellationToken, true).SuppressContextFlow<int>();
                }
                else
                {
                    bytesRead = await base.ReadAsync(buffer, 0, 1, linkedCancellationToken).SuppressContextFlow<int>();
                }

                if (bytesRead != 0)
                {
                    Contract.Assert(false, "'bytesRead' MUST be '0' at this point. Instead more payload was received ('" + buffer[0].ToString() + "')");

                    if (WebSocketBase.LoggingEnabled)
                    {
                        Logging.Dump(Logging.WebSockets, this, Methods.CloseNetworkConnectionAsync, buffer, 0, bytesRead);
                    }

                    throw new WebSocketException(WebSocketError.NotAWebSocket);
                }
            }
            catch (Exception error)
            {
                if (!s_CanHandleException(error))
                {
                    throw;
                }

                // throw OperationCancelledException when canceled by the caller
                // ignore cancellation due to the timeout
                cancellationToken.ThrowIfCancellationRequested();
            }
            finally
            {
                cancellationTokenRegistration.Dispose();
                if (linkedCancellationTokenSource != null)
                {
                    linkedCancellationTokenSource.Dispose();
                }

                if (reasonableTimeoutCancellationTokenSource != null)
                {
                    reasonableTimeoutCancellationTokenSource.Dispose();
                }

                if (WebSocketBase.LoggingEnabled)
                {
                    Logging.Exit(Logging.WebSockets, this, Methods.CloseNetworkConnectionAsync, bytesRead);
                }
            }
        }
开发者ID:iskiselev,项目名称:JSIL.NetFramework,代码行数:79,代码来源:WebSocketConnectionStream.cs

示例11: MultipleWriteAsync

        public async Task MultipleWriteAsync(IList<ArraySegment<byte>> sendBuffers, CancellationToken cancellationToken)
        {
            Contract.Assert(this.SupportsMultipleWrite, "This method MUST NOT be used for custom NetworkStream implementations.");

            if (WebSocketBase.LoggingEnabled)
            {
                Logging.Enter(Logging.WebSockets, this, Methods.MultipleWriteAsync, string.Empty);
            }
            CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();

            try
            {
                if (cancellationToken.CanBeCanceled)
                {
                    cancellationTokenRegistration = cancellationToken.Register(s_OnCancel, this, false);
                }

                WebSocketHelpers.ThrowIfConnectionAborted(m_ConnectStream.Connection, false);
                await ((WebSocketBase.IWebSocketStream)base.BaseStream).MultipleWriteAsync(sendBuffers, cancellationToken).SuppressContextFlow();

                if (WebSocketBase.LoggingEnabled)
                {
                    foreach(ArraySegment<byte> buffer in sendBuffers)
                    {
                        Logging.Dump(Logging.WebSockets, this, Methods.MultipleWriteAsync, buffer.Array, buffer.Offset, buffer.Count);
                    }
                }
            }
            catch (Exception error)
            {
                if (s_CanHandleException(error))
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }

                throw;
            }
            finally
            {
                cancellationTokenRegistration.Dispose();

                if (WebSocketBase.LoggingEnabled)
                {
                    Logging.Exit(Logging.WebSockets, this, Methods.MultipleWriteAsync, string.Empty);
                }
            }
        }
开发者ID:iskiselev,项目名称:JSIL.NetFramework,代码行数:47,代码来源:WebSocketConnectionStream.cs

示例12: WriteAsync

        public async override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            if (WebSocketBase.LoggingEnabled)
            {
                Logging.Enter(Logging.WebSockets, this, Methods.WriteAsync,
                    WebSocketHelpers.GetTraceMsgForParameters(offset, count, cancellationToken));
            }
            CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();

            try
            {
                if (cancellationToken.CanBeCanceled)
                {
                    cancellationTokenRegistration = cancellationToken.Register(s_OnCancel, this, false);
                }

                WebSocketHelpers.ThrowIfConnectionAborted(m_ConnectStream.Connection, false);
                await base.WriteAsync(buffer, offset, count, cancellationToken).SuppressContextFlow();

                if (WebSocketBase.LoggingEnabled)
                {
                    Logging.Dump(Logging.WebSockets, this, Methods.WriteAsync, buffer, offset, count);
                }
            }
            catch (Exception error)
            {
                if (s_CanHandleException(error))
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }

                throw;
            }
            finally
            {
                cancellationTokenRegistration.Dispose();

                if (WebSocketBase.LoggingEnabled)
                {
                    Logging.Exit(Logging.WebSockets, this,  Methods.WriteAsync, string.Empty);
                }
            }
        }
开发者ID:iskiselev,项目名称:JSIL.NetFramework,代码行数:43,代码来源:WebSocketConnectionStream.cs

示例13: ConnectAsyncCore

        private async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken)
        {
            HttpWebResponse response = null;
            CancellationTokenRegistration connectCancellation = new CancellationTokenRegistration();
            // Any errors from here on out are fatal and this instance will be disposed.
            try
            {
                HttpWebRequest request = CreateAndConfigureRequest(uri);
                if (Logging.On) Logging.Associate(Logging.WebSockets, this, request);

                connectCancellation = cancellationToken.Register(AbortRequest, request, false);

                response = await request.GetResponseAsync().SuppressContextFlow() as HttpWebResponse;
                Contract.Assert(response != null, "Not an HttpWebResponse");

                if (Logging.On) Logging.Associate(Logging.WebSockets, this, response);

                string subprotocol = ValidateResponse(request, response);

                innerWebSocket = WebSocket.CreateClientWebSocket(response.GetResponseStream(), subprotocol,
                    options.ReceiveBufferSize, options.SendBufferSize, options.KeepAliveInterval, false,
                    options.GetOrCreateBuffer());

                if (Logging.On) Logging.Associate(Logging.WebSockets, this, innerWebSocket);

                // Change internal state to 'connected' to enable the other methods
                if (Interlocked.CompareExchange(ref state, connected, connecting) != connecting)
                {
                    // Aborted/Disposed during connect.
                    throw new ObjectDisposedException(GetType().FullName);
                }
            }
            catch (WebException ex)
            {
                ConnectExceptionCleanup(response);
                WebSocketException wex = new WebSocketException(SR.GetString(SR.net_webstatus_ConnectFailure), ex);
                if (Logging.On) Logging.Exception(Logging.WebSockets, this, "ConnectAsync", wex);
                throw wex;
            }
            catch (Exception ex)
            {
                ConnectExceptionCleanup(response);
                if (Logging.On) Logging.Exception(Logging.WebSockets, this, "ConnectAsync", ex);
                throw;
            }
            finally
            {
                // We successfully connected (or failed trying), disengage from this token.  
                // Otherwise any timeout/cancellation would apply to the full session.
                // In the failure case we need to release the reference to HWR.
                connectCancellation.Dispose();
            }
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:53,代码来源:ClientWebSocket.cs

示例14: CloseNetworkConnectionAsync

        public async Task CloseNetworkConnectionAsync(CancellationToken cancellationToken)
        {
            // need to yield here to make sure that we don't get any exception synchronously
            await Task.Yield();

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this);
            }

            CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();

            try
            {
                if (cancellationToken.CanBeCanceled)
                {
                    cancellationTokenRegistration = cancellationToken.Register(s_OnCancel, this, false);
                }
#if DEBUG
                // When using fast path only one outstanding read is permitted. By switching into opaque mode
                // via IWebSocketStream.SwitchToOpaqueMode (see more detailed comments in interface definition)
                // caller takes responsibility for enforcing this constraint.
                Debug.Assert(Interlocked.Increment(ref _outstandingOperations._writes) == 1,
                    "Only one outstanding write allowed at any given time.");
#endif
                _writeTaskCompletionSource = new TaskCompletionSource<object>();
                _writeEventArgs.SetShouldCloseOutput();
                if (WriteAsyncFast(_writeEventArgs))
                {
                    await _writeTaskCompletionSource.Task.SuppressContextFlow();
                }
            }
            catch (Exception error)
            {
                if (!s_CanHandleException(error))
                {
                    throw;
                }

                // throw OperationCancelledException when canceled by the caller
                // otherwise swallow the exception
                cancellationToken.ThrowIfCancellationRequested();
            }
            finally
            {
                cancellationTokenRegistration.Dispose();

                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Exit(this);
                }
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:53,代码来源:WebSocketHttpListenerDuplexStream.cs

示例15: SaveChanges

        /// <summary>
        /// If AutoSaveChanges is set this method will auto commit changes
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected virtual Task<int> SaveChanges(CancellationToken cancellationToken)
        {
            var source = new TaskCompletionSource<int>();
            if (AutoSaveChanges) {
                var registration = new CancellationTokenRegistration();
                if (cancellationToken.CanBeCanceled) {
                    if (cancellationToken.IsCancellationRequested) {
                        source.SetCanceled();
                        return source.Task;
                    }
                    registration = cancellationToken.Register(CancelIgnoreFailure);
                }

                try
                {
                    return _uow.SaveChangesAsync(cancellationToken);
                }
                catch (Exception e)
                {
                    source.SetException(e);
                }
                finally
                {
                    registration.Dispose();
                }
            }
            return source.Task;
        }
开发者ID:rubenknuijver,项目名称:Jigsaw,代码行数:33,代码来源:DataStore.cs


注:本文中的System.Threading.CancellationTokenRegistration.Dispose方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。