本文整理汇总了C#中System.Threading.CancellationToken.SafeRegister方法的典型用法代码示例。如果您正苦于以下问题:C# CancellationToken.SafeRegister方法的具体用法?C# CancellationToken.SafeRegister怎么用?C# CancellationToken.SafeRegister使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.CancellationToken
的用法示例。
在下文中一共展示了CancellationToken.SafeRegister方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TransportInitializationHandler
public TransportInitializationHandler(IHttpClient httpClient,
IConnection connection,
string connectionData,
string transport,
CancellationToken disconnectToken)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
_connection = connection;
_httpClient = httpClient;
_connectionData = connectionData;
_transport = transport;
_initializationTask = new TaskCompletionSource<object>();
_initializationInvoker = new ThreadSafeInvoker();
// Default event
OnFailure = () => { };
// We want to fail if the disconnect token is tripped while we're waiting on initialization
_tokenCleanup = disconnectToken.SafeRegister(_ =>
{
Fail();
},
state: null);
TaskAsyncHelper.Delay(connection.TotalTransportConnectTimeout).Then(() =>
{
Fail(new TimeoutException(Resources.Error_TransportTimedOutTryingToConnect));
});
}
示例2: InitializeResolverDispose
private static void InitializeResolverDispose(this IDependencyResolver resolver, CancellationToken hostShutdownToken)
{
// TODO: Guard against multiple calls to this
// When the host triggers the shutdown token, dispose the resolver
hostShutdownToken.SafeRegister(state =>
{
((IDependencyResolver)state).Dispose();
},
resolver);
}
示例3: OnStart
protected override void OnStart(IConnection connection, string connectionData, CancellationToken disconnectToken)
{
_disconnectRegistration = disconnectToken.SafeRegister(state =>
{
// _reconnectInvoker can be null if disconnectToken is tripped before the polling loop is started
if (_reconnectInvoker != null)
{
_reconnectInvoker.Invoke();
}
StopPolling();
}, null);
StartPolling(connection, connectionData);
}
示例4: TransportInitializationHandler
public TransportInitializationHandler(TimeSpan failureTimeout, CancellationToken disconnectToken)
{
_initializationTask = new TaskCompletionSource<object>();
_initializationInvoker = new ThreadSafeInvoker();
// Default event
OnFailure = () => { };
// We want to fail if the disconnect token is tripped while we're waiting on initialization
_tokenCleanup = disconnectToken.SafeRegister(_ =>
{
Fail();
},
state: null);
TaskAsyncHelper.Delay(failureTimeout).Then(() =>
{
Fail(new TimeoutException(Resources.Error_TransportTimedOutTryingToConnect));
});
}
示例5: TransportInitializationHandler
public TransportInitializationHandler(IHttpClient httpClient,
IConnection connection,
string connectionData,
string transport,
CancellationToken disconnectToken,
TransportHelper transportHelper)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
_connection = connection;
_httpClient = httpClient;
_connectionData = connectionData;
_transport = transport;
_transportHelper = transportHelper;
_initializationTask = new TaskCompletionSource<object>();
_initializationInvoker = new ThreadSafeInvoker();
// Default event
OnFailure = () => { };
// We want to fail if the disconnect token is tripped while we're waiting on initialization
_tokenCleanup = disconnectToken.SafeRegister(
_ => Fail(new OperationCanceledException(Resources.Error_ConnectionCancelled, disconnectToken)),
state: null);
TaskAsyncHelper.Delay(connection.TotalTransportConnectTimeout)
.Then(() =>
{
// don't timeout once connect request has finished
if (Interlocked.CompareExchange(ref _state, InitializationState.Failed, InitializationState.Initial) ==
InitializationState.Initial)
{
Fail(new TimeoutException(Resources.Error_TransportTimedOutTryingToConnect));
}
});
}
示例6: OpenConnection
private void OpenConnection(IConnection connection,
string data,
CancellationToken disconnectToken,
Action initializeCallback,
Action<Exception> errorCallback)
{
// If we're reconnecting add /connect to the url
bool reconnecting = initializeCallback == null;
var callbackInvoker = new ThreadSafeInvoker();
var requestDisposer = new Disposer();
var url = (reconnecting ? connection.Url : connection.Url + "connect") + GetReceiveQueryString(connection, data);
connection.Trace(TraceLevels.Events, "SSE: GET {0}", url);
HttpClient.Get(url, req =>
{
_request = req;
connection.PrepareRequest(_request);
_request.Accept = "text/event-stream";
}).ContinueWith(task =>
{
if (task.IsFaulted)
{
Exception exception = task.Exception.Unwrap();
if (!ExceptionHelper.IsRequestAborted(exception))
{
if (errorCallback != null)
{
callbackInvoker.Invoke((cb, ex) => cb(ex), errorCallback, exception);
}
else if (reconnecting)
{
// Only raise the error event if we failed to reconnect
connection.OnError(exception);
Reconnect(connection, data, disconnectToken);
}
}
requestDisposer.Dispose();
}
else
{
var response = task.Result;
Stream stream = response.GetStream();
var eventSource = new EventSourceStreamReader(connection, stream);
bool retry = true;
var esCancellationRegistration = disconnectToken.SafeRegister(state =>
{
retry = false;
((IRequest)state).Abort();
},
_request);
eventSource.Opened = () =>
{
// If we're not reconnecting, then we're starting the transport for the first time. Trigger callback only on first start.
if (!reconnecting)
{
callbackInvoker.Invoke(initializeCallback);
}
else if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
{
// Raise the reconnect event if the connection comes back up
connection.OnReconnected();
}
};
eventSource.Message = sseEvent =>
{
if (sseEvent.EventType == EventType.Data)
{
if (sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase))
{
return;
}
bool timedOut;
bool disconnected;
TransportHelper.ProcessResponse(connection, sseEvent.Data, out timedOut, out disconnected);
if (disconnected)
{
retry = false;
connection.Disconnect();
}
}
};
eventSource.Closed = exception =>
{
if (exception != null)
{
// Check if the request is aborted
bool isRequestAborted = ExceptionHelper.IsRequestAborted(exception);
//.........这里部分代码省略.........
示例7: OpenConnection
internal void OpenConnection(IConnection connection, string data, CancellationToken disconnectToken, bool reconnecting)
{
// If we're reconnecting add /connect to the url
var url = reconnecting
? UrlBuilder.BuildReconnect(connection, Name, data)
: UrlBuilder.BuildConnect(connection, Name, data);
connection.Trace(TraceLevels.Events, "SSE: GET {0}", url);
var getTask = HttpClient.Get(url, req =>
{
_request = req;
_request.Accept = "text/event-stream";
connection.PrepareRequest(_request);
}, isLongRunning: true);
var requestCancellationRegistration = disconnectToken.SafeRegister(state =>
{
_stop = true;
// This will no-op if the request is already finished.
((IRequest)state).Abort();
}, _request);
getTask.ContinueWith(task =>
{
if (task.IsFaulted || task.IsCanceled)
{
var exception = task.IsCanceled
? new OperationCanceledException(Resources.Error_TaskCancelledException)
: task.Exception.Unwrap();
if (!reconnecting)
{
TransportFailed(exception);
}
else if (!_stop)
{
// Only raise the error event if we failed to reconnect
connection.OnError(exception);
Reconnect(connection, data, disconnectToken);
}
requestCancellationRegistration.Dispose();
}
else
{
// If the disconnect token is canceled the response to the task doesn't matter.
if (disconnectToken.IsCancellationRequested)
{
return;
}
var response = task.Result;
Stream stream = response.GetStream();
var eventSource = new EventSourceStreamReader(connection, stream);
eventSource.Opened = () =>
{
// This will noop if we're not in the reconnecting state
if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
{
// Raise the reconnect event if the connection comes back up
connection.OnReconnected();
}
};
eventSource.Message = sseEvent =>
{
if (sseEvent.EventType == EventType.Data &&
!sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase))
{
ProcessResponse(connection, sseEvent.Data);
}
};
eventSource.Closed = exception =>
{
if (exception != null)
{
// Check if the request is aborted
if (!ExceptionHelper.IsRequestAborted(exception))
{
// Don't raise exceptions if the request was aborted (connection was stopped).
connection.OnError(exception);
}
}
requestCancellationRegistration.Dispose();
response.Dispose();
if (_stop)
{
AbortHandler.CompleteAbort();
}
else if (AbortHandler.TryCompleteAbort())
//.........这里部分代码省略.........
示例8: InitializePersistentState
protected virtual Task InitializePersistentState()
{
_hostShutdownToken = _context.Environment.GetShutdownToken();
_requestLifeTime = new HttpRequestLifeTime(this, WriteQueue, Trace, ConnectionId);
// Create the TCS that completes when the task returned by PersistentConnection.OnConnected does.
_connectTcs = new TaskCompletionSource<object>();
// Create a token that represents the end of this connection's life
_connectionEndTokenSource = new SafeCancellationTokenSource();
_connectionEndToken = _connectionEndTokenSource.Token;
// Handle the shutdown token's callback so we can end our token if it trips
_hostRegistration = _hostShutdownToken.SafeRegister(state =>
{
((SafeCancellationTokenSource)state).Cancel();
},
_connectionEndTokenSource);
// When the connection ends release the request
_connectionEndRegistration = CancellationToken.SafeRegister(state =>
{
((HttpRequestLifeTime)state).Complete();
},
_requestLifeTime);
return InitializeMessageId();
}
示例9: PollingLoop
//.........这里部分代码省略.........
shouldRaiseReconnect = true;
// Get the underlying exception
Exception exception = task.Exception.Unwrap();
// If the error callback isn't null then raise it and don't continue polling
if (errorCallback != null)
{
callbackInvoker.Invoke((cb, ex) => cb(ex), errorCallback, exception);
}
else
{
// Figure out if the request was aborted
requestAborted = ExceptionHelper.IsRequestAborted(exception);
// Sometimes a connection might have been closed by the server before we get to write anything
// so just try again and don't raise OnError.
if (!requestAborted && !(exception is IOException))
{
// Raise on error
connection.OnError(exception);
// If the connection is still active after raising the error event wait for 2 seconds
// before polling again so we aren't hammering the server
TaskAsyncHelper.Delay(ErrorDelay).Then(() =>
{
if (!disconnectToken.IsCancellationRequested)
{
PollingLoop(connection,
data,
disconnectToken,
initializeCallback: null,
errorCallback: null,
raiseReconnect: shouldRaiseReconnect);
}
});
}
}
}
else
{
if (!disconnectToken.IsCancellationRequested)
{
// Continue polling if there was no error
PollingLoop(connection,
data,
disconnectToken,
initializeCallback: null,
errorCallback: null,
raiseReconnect: shouldRaiseReconnect);
}
}
}
requestDisposer.Dispose();
}
});
var requestCancellationRegistration = disconnectToken.SafeRegister(req =>
{
if (req != null)
{
// This will no-op if the request is already finished.
req.Abort();
}
// Prevent the connection state from switching to the reconnected state.
reconnectInvoker.Invoke();
if (errorCallback != null)
{
callbackInvoker.Invoke((cb, token) =>
{
#if NET35 || WINDOWS_PHONE
cb(new OperationCanceledException(Resources.Error_ConnectionCancelled));
#else
cb(new OperationCanceledException(Resources.Error_ConnectionCancelled, token));
#endif
}, errorCallback, disconnectToken);
}
}, request);
requestDisposer.Set(requestCancellationRegistration);
if (initializeCallback != null)
{
TaskAsyncHelper.Delay(ConnectDelay).Then(() =>
{
callbackInvoker.Invoke(initializeCallback);
});
}
if (raiseReconnect)
{
TaskAsyncHelper.Delay(ReconnectDelay).Then(() =>
{
// Fire the reconnect event after the delay. This gives the
reconnectInvoker.Invoke((conn) => FireReconnected(conn), connection);
});
}
}
示例10: OpenConnection
private void OpenConnection(IConnection connection,
string data,
CancellationToken disconnectToken,
Action initializeCallback,
Action<Exception> errorCallback)
{
// If we're reconnecting add /connect to the url
bool reconnecting = initializeCallback == null;
var callbackInvoker = new ThreadSafeInvoker();
var requestDisposer = new Disposer();
var url = (reconnecting ? connection.Url : connection.Url + "connect") + GetReceiveQueryString(connection, data);
IRequest request = null;
#if NET35
Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "SSE: GET {0}", (object)url));
#else
Debug.WriteLine("SSE: GET {0}", (object)url);
#endif
HttpClient.Get(url, req =>
{
request = req;
connection.PrepareRequest(request);
request.Accept = "text/event-stream";
}).ContinueWith(task =>
{
if (task.IsFaulted)
{
Exception exception = task.Exception.Unwrap();
if (!ExceptionHelper.IsRequestAborted(exception))
{
if (errorCallback != null)
{
callbackInvoker.Invoke((cb, ex) => cb(ex), errorCallback, exception);
}
else if (reconnecting)
{
// Only raise the error event if we failed to reconnect
connection.OnError(exception);
Reconnect(connection, data, disconnectToken);
}
}
requestDisposer.Dispose();
}
else
{
IResponse response = task.Result;
Stream stream = response.GetResponseStream();
var eventSource = new EventSourceStreamReader(stream);
bool retry = true;
var esCancellationRegistration = disconnectToken.SafeRegister(es =>
{
retry = false;
es.Close();
}, eventSource);
eventSource.Opened = () =>
{
if (!reconnecting)
{
callbackInvoker.Invoke(initializeCallback);
}
else if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
{
// Raise the reconnect event if the connection comes back up
connection.OnReconnected();
}
};
eventSource.Message = sseEvent =>
{
if (sseEvent.EventType == EventType.Data)
{
if (sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase))
{
return;
}
bool timedOut;
bool disconnected;
TransportHelper.ProcessResponse(connection, sseEvent.Data, out timedOut, out disconnected);
if (disconnected)
{
retry = false;
connection.Disconnect();
}
}
};
eventSource.Closed = exception =>
{
bool isRequestAborted = false;
if (exception != null)
//.........这里部分代码省略.........
示例11: InitializePersistentState
protected virtual void InitializePersistentState()
{
_hostShutdownToken = _context.HostShutdownToken();
Completed = new TaskCompletionSource<object>();
// Create a token that represents the end of this connection's life
_connectionEndTokenSource = new SafeCancellationTokenSource();
_connectionEndToken = _connectionEndTokenSource.Token;
// Handle the shutdown token's callback so we can end our token if it trips
_hostRegistration = _hostShutdownToken.SafeRegister(state =>
{
state.Cancel();
},
_connectionEndTokenSource);
}
示例12: OpenConnection
private void OpenConnection(IConnection connection,
string data,
CancellationToken disconnectToken,
Action initializeCallback,
Action<Exception> errorCallback)
{
// If we're reconnecting add /connect to the url
bool reconnecting = initializeCallback == null;
var callbackInvoker = new ThreadSafeInvoker();
var requestDisposer = new Disposer();
Action initializeInvoke = () =>
{
callbackInvoker.Invoke(initializeCallback);
};
var url = connection.Url + (reconnecting ? "reconnect" : "connect") + GetReceiveQueryString(connection, data);
connection.Trace(TraceLevels.Events, "SSE: GET {0}", url);
HttpClient.Get(url, req =>
{
_request = req;
_request.Accept = "text/event-stream";
connection.PrepareRequest(_request);
}, isLongRunning: true).ContinueWith(task =>
{
if (task.IsFaulted || task.IsCanceled)
{
Exception exception;
if (task.IsCanceled)
{
exception = new OperationCanceledException(Resources.Error_TaskCancelledException);
}
else
{
exception = task.Exception.Unwrap();
}
if (errorCallback != null)
{
callbackInvoker.Invoke((cb, ex) => cb(ex), errorCallback, exception);
}
else if (!_stop && reconnecting)
{
// Only raise the error event if we failed to reconnect
connection.OnError(exception);
Reconnect(connection, data, disconnectToken);
}
requestDisposer.Dispose();
}
else
{
// If the disconnect token is canceled the response to the task doesn't matter.
if (disconnectToken.IsCancellationRequested)
{
return;
}
var response = task.Result;
Stream stream = response.GetStream();
var eventSource = new EventSourceStreamReader(connection, stream);
var esCancellationRegistration = disconnectToken.SafeRegister(state =>
{
_stop = true;
((IRequest)state).Abort();
},
_request);
eventSource.Opened = () =>
{
// This will noop if we're not in the reconnecting state
if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
{
// Raise the reconnect event if the connection comes back up
connection.OnReconnected();
}
};
eventSource.Message = sseEvent =>
{
if (sseEvent.EventType == EventType.Data)
{
if (sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase))
{
return;
}
bool shouldReconnect;
bool disconnected;
TransportHelper.ProcessResponse(connection, sseEvent.Data, out shouldReconnect, out disconnected, initializeInvoke);
if (disconnected)
{
_stop = true;
//.........这里部分代码省略.........
示例13: PollingSetup
private void PollingSetup(IConnection connection,
string data,
CancellationToken disconnectToken,
PollingRequestHandler requestHandler,
Action onInitialized)
{
// reconnectInvoker is created new on each poll
var reconnectInvoker = new ThreadSafeInvoker();
var disconnectRegistration = disconnectToken.SafeRegister(state =>
{
reconnectInvoker.Invoke();
requestHandler.Stop();
}, null);
requestHandler.ResolveUrl = () =>
{
var url = connection.Url;
if (connection.MessageId == null)
{
url += "connect";
connection.Trace(TraceLevels.Events, "LP Connect: {0}", url);
}
else if (IsReconnecting(connection))
{
url += "reconnect";
connection.Trace(TraceLevels.Events, "LP Reconnect: {0}", url);
}
else
{
url += "poll";
connection.Trace(TraceLevels.Events, "LP Poll: {0}", url);
}
url += GetReceiveQueryString(connection, data);
return url;
};
requestHandler.PrepareRequest += req =>
{
connection.PrepareRequest(req);
};
requestHandler.OnMessage += message =>
{
var shouldReconnect = false;
var disconnectedReceived = false;
connection.Trace(TraceLevels.Messages, "LP: OnMessage({0})", message);
TransportHelper.ProcessResponse(connection,
message,
out shouldReconnect,
out disconnectedReceived,
onInitialized);
if (IsReconnecting(connection))
{
// If the timeout for the reconnect hasn't fired as yet just fire the
// event here before any incoming messages are processed
TryReconnect(connection, reconnectInvoker);
}
if (shouldReconnect)
{
// Transition into reconnecting state
connection.EnsureReconnecting();
}
if (disconnectedReceived)
{
connection.Disconnect();
}
};
requestHandler.OnError += exception =>
{
reconnectInvoker.Invoke();
// Transition into reconnecting state
connection.EnsureReconnecting();
// Sometimes a connection might have been closed by the server before we get to write anything
// so just try again and raise OnError.
if (!ExceptionHelper.IsRequestAborted(exception) && !(exception is IOException))
{
connection.OnError(exception);
}
else
{
requestHandler.Stop();
}
};
requestHandler.OnPolling += () =>
{
// Capture the cleanup within a closure so it can persist through multiple requests
TryDelayedReconnect(connection, reconnectInvoker);
//.........这里部分代码省略.........
示例14: InitializePersistentState
protected virtual void InitializePersistentState()
{
_hostShutdownToken = _context.HostShutdownToken();
_requestLifeTime = new HttpRequestLifeTime(WriteQueue, Trace, ConnectionId);
// Create a token that represents the end of this connection's life
_connectionEndTokenSource = new SafeCancellationTokenSource();
_connectionEndToken = _connectionEndTokenSource.Token;
// Handle the shutdown token's callback so we can end our token if it trips
_hostRegistration = _hostShutdownToken.SafeRegister(state =>
{
((SafeCancellationTokenSource)state).Cancel();
},
_connectionEndTokenSource);
// When the connection ends release the request
_connectionEndRegistration = CancellationToken.SafeRegister(state =>
{
((HttpRequestLifeTime)state).Complete();
},
_requestLifeTime);
}