本文整理汇总了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 ();
}
示例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;
}
示例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;
}
示例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);
}
}
}
示例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);
}
}
}
示例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();
}
}
示例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);
}
}
}
示例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);
}
示例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;
}
示例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);
}
}
}
示例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);
}
}
}
示例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);
}
}
}
示例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();
}
}
示例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);
}
}
}
示例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;
}