本文整理汇总了C#中CancellationToken.Register方法的典型用法代码示例。如果您正苦于以下问题:C# CancellationToken.Register方法的具体用法?C# CancellationToken.Register怎么用?C# CancellationToken.Register使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类CancellationToken
的用法示例。
在下文中一共展示了CancellationToken.Register方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DelayTask
public DelayTask(CancellationToken cancellationToken, int millisecondsDelay)
{
if (cancellationToken.CanBeCanceled)
{
cancellationToken.Register(Complete, false);
}
if (millisecondsDelay != Timeout.Infinite)
{
m_timer = new Timer(_ => Complete(), null, millisecondsDelay, Timeout.Infinite);
}
m_cancellationToken = cancellationToken;
}
示例2: Delay
/// <summary>
/// 遅延後に完了するタスクを作成します。
/// </summary>
/// <param name="span">返されたタスクを完了する前に待機する時間。</param>
/// <param name="ct"></param>
/// <returns></returns>
public static Task Delay(TimeSpan span, CancellationToken ct)
{
var ms = span.TotalMilliseconds;
if (ms < 0)
return Task.CompletedTask;
// Delayの最大待ち時間(約4年)より長い場合はキャンセルされるまで待つタスクになる
if(int.MaxValue < ms)
{
var tcs = new TaskCompletionSource<object>();
ct.Register(() => tcs.SetResult(default(object)));
return tcs.Task;
}
return Delay((int)ms, ct, null);
}
示例3: LockAsync
/// <summary>
/// Asynchronously acquires the lock. Returns a disposable that releases the lock when disposed.
/// </summary>
/// <returns>A disposable that releases the lock when disposed.</returns>
public Task<IDisposable> LockAsync(CancellationToken token)
{
TaskCompletionSource<IDisposable> tcs = new TaskCompletionSource<IDisposable>();
lock (queue)
{
// If the lock is available, take it immediately and return.
if (!taken)
{
taken = true;
tcs.SetResult(new Key(this));
return tcs.Task;
}
#region Optional but nice behavior
// If the CancellationToken is signalled, cancel synchronously before entering the queue.
if (token.IsCancellationRequested)
{
tcs.SetCanceled();
return tcs.Task;
}
#endregion
// Wait for the lock to become available (or cancellation).
queue.Add(tcs);
} // (release lock)
// We have to run this outside the lock because Register may run its delegate synchronously.
if (token.CanBeCanceled)
{
token.Register(() =>
{
lock (queue)
{
if (!queue.Remove(tcs))
return;
}
// Again, complete the TCS *outside* any locks!
tcs.SetCanceled();
}, useSynchronizationContext: false);
}
return tcs.Task;
}
示例4: StartNewDelayed
/// <summary>Creates a Task that will complete after the specified delay.</summary>
/// <param name="factory">The TaskFactory.</param>
/// <param name="millisecondsDelay">The delay after which the Task should transition to RanToCompletion.</param>
/// <param name="cancellationToken">The cancellation token that can be used to cancel the timed task.</param>
/// <returns>A Task that will be completed after the specified duration and that's cancelable with the specified token.</returns>
public static Task StartNewDelayed(this TaskFactory factory, int millisecondsDelay, CancellationToken cancellationToken)
{
// Validate arguments
if (factory == null) throw new ArgumentNullException("factory");
if (millisecondsDelay < 0) throw new ArgumentOutOfRangeException("millisecondsDelay");
// Check for a pre-canceled token
if (cancellationToken.IsCancellationRequested)
return factory.FromCancellation(cancellationToken);
// Create the timed task
var tcs = new TaskCompletionSource<object>(factory.CreationOptions);
var ctr = default(CancellationTokenRegistration);
// Create the timer but don't start it yet. If we start it now,
// it might fire before ctr has been set to the right registration.
var timer = new Timer(self =>
{
// Clean up both the cancellation token and the timer, and try to transition to completed
ctr.Dispose();
((Timer)self).Dispose();
tcs.TrySetResult(null);
});
// Register with the cancellation token.
if (cancellationToken.CanBeCanceled)
{
// When cancellation occurs, cancel the timer and try to transition to canceled.
// There could be a race, but it's benign.
ctr = cancellationToken.Register(() =>
{
timer.Dispose();
tcs.TrySetCanceled();
});
}
// Start the timer and hand back the task...
try { timer.Change(millisecondsDelay, Timeout.Infinite); }
catch(ObjectDisposedException) {} // in case there's a race with cancellation; this is benign
return tcs.Task;
}
示例5: FetchJSON
void FetchJSON(HttpsRequest request, Action<JsonValue> completion, Action<Exception> errorHandler, CancellationToken token)
{
var op = System.ComponentModel.AsyncOperationManager.CreateOperation(null);
request.UserAgent = "FlashcardsWP7/0.1 (" + Environment.OSVersion + "; .NET " + Environment.Version + ")";
try {
token.Register(delegate { throw new OperationCanceledException(); });
ThreadPool.QueueUserWorkItem(
_ => {
Exception error;
try {
var client = new HttpsClient(Host.Host, Host.Port, Configuration.VerifyCertificates);
var response = client.MakeRequest(request);
var text = response.DecodeTextBody();
if (response.StatusCode == 204) {
op.PostOperationCompleted(delegate { completion(null); }, null);
return;
}
var json = JsonValue.Parse(new StringReader(text));
if (response.StatusCode / 100 != 2) {
var dict = (JsonDictionary) json;
var errorCode = new JsonContext().FromJson<string>(dict.Items["error"]);
var errorText = new JsonContext().FromJson<string>(dict.Items["error_description"]);
if (errorCode != null && errorText != null) {
// TODO: find error code for needing password
if (errorCode == "invalid_access")
throw new AccessDeniedException(errorText);
if (errorCode == "item_not_found")
throw new ItemNotFoundException(errorText);
if (errorCode == "item_deleted")
throw new ItemDeletedException(errorText);
throw new QuizletException(errorText);
}
throw new QuizletException("The Quizlet request failed (HTTP error " + response.StatusCode.ToString(CultureInfo.InvariantCulture) + ").");
}
op.PostOperationCompleted(delegate { completion(json); }, null);
return;
}
catch (QuizletException e) {
error = e;
}
catch (OperationCanceledException e) {
error = e;
}
catch (HttpException e) {
error = e;
}
catch (System.Net.Sockets.SocketException e) {
error = e;
}
catch (IOException e) {
error = e;
}
catch (ArgumentException e) {
error = e;
}
catch (InvalidOperationException e) {
error = e;
}
catch (NotSupportedException e) {
error = e;
}
catch (FormatException e) {
error = new QuizletException("The Quizlet server returned an invalid document.", e);
}
catch (JsonConvertException e) {
error = new QuizletException("The Quizlet server returned an invalid document.", e);
}
catch (InvalidCastException e) {
error = new QuizletException("The Quizlet server returned an invalid document.", e);
}
catch (KeyNotFoundException e) {
error = new QuizletException("The Quizlet server returned an invalid document.", e);
}
op.PostOperationCompleted(delegate { errorHandler(error); }, null);
});
} catch (OperationCanceledException e) {
errorHandler(e);
}
}
示例6: Wait
public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
{
bool result;
cancellationToken.Register(Cancel);
if (millisecondsTimeout != Timeout.Infinite)
{
result = Event.Await(millisecondsTimeout, TimeUnit.MILLISECONDS);
}
else
{
Event.Await();
result = true;
}
cancellationToken.ThrowIfCancellationRequested();
return result;
}
示例7: Wait
public bool Wait(int millisTimeout, CancellationToken ctk) {
ctk.ThrowIfCancellationRequested();
if (millisTimeout < Timeout.Infinite)
throw new ArgumentOutOfRangeException("millisTimeout");
if (IsSet) {
return true;
}
if (millisTimeout == 0)
return false;
int expiresTickCount = 0;
bool timedOut = false;
int timeout = millisTimeout;
if (millisTimeout != Timeout.Infinite) {
expiresTickCount = Environment.TickCount + millisTimeout;
timedOut = true;
}
int defaultSpin = DEFAULT_SPIN_MP; // 10
int sleep0Modulus = DEFAULT_SPIN_MP / 2;
int sleep1Modulus = DEFAULT_SPIN_MP * 2;
int spinCount = SpinCount;
for (int i = 0; i < spinCount; i++) {
if (IsSet)
return true;
if (i < defaultSpin) {
if (i == (defaultSpin / 2)) {
Thread.Yield();
} else {
Thread.SpinWait(Environment.ProcessorCount * (((int) 4) << i));
}
} else if ((i % sleep1Modulus) == 0) {
Thread.Sleep(1);
} else if ((i % sleep0Modulus) == 0) {
Thread.Sleep(0);
} else {
Thread.Yield();
}
//
// Check if the wait was cancelled.
//
if (i >= 100 && (i % 10) == 0) {
ctk.ThrowIfCancellationRequested();
}
}
EnsureLockObjectCreated();
using (ctk.Register(s_cancellationTokenCallback, this)) {
lock (m_lock) {
int entryStateVersion = stateVersion;
do {
if (IsSet || entryStateVersion != stateVersion) {
return true;
}
ctk.ThrowIfCancellationRequested();
//
// Adjust timeout, if any
//
if (timedOut) {
int now = Environment.TickCount;
if (expiresTickCount <= now)
return false;
timeout = expiresTickCount - now;
}
//
// Increment waiters, and check IsSet again
//
Waiters++;
if (IsSet) {
Waiters--;
return true;
}
try {
if (!Monitor.Wait(m_lock, timeout)) {
return false;
}
} finally {
Waiters--;
}
} while (true);
}
}
}
示例8: Initialize
/// <summary>
/// Initializes the performance counters.
/// </summary>
/// <param name="instanceName">The host instance name.</param>
/// <param name="hostShutdownToken">The CancellationToken representing the host shutdown.</param>
public void Initialize(string instanceName, CancellationToken hostShutdownToken)
{
if (_initialized)
{
return;
}
var needToRegisterWithShutdownToken = false;
lock (_initLocker)
{
if (!_initialized)
{
InstanceName = SanitizeInstanceName(instanceName);
SetCounterProperties();
// The initializer ran, so let's register the shutdown cleanup
if (hostShutdownToken != CancellationToken.None)
{
needToRegisterWithShutdownToken = true;
}
_initialized = true;
}
}
if (needToRegisterWithShutdownToken)
{
hostShutdownToken.Register(UnloadCounters);
}
}
示例9: AssignCancellationToken
private void AssignCancellationToken(CancellationToken cancellationToken, Task antecedent, TaskContinuation continuation)
{
CancellationToken = cancellationToken;
try
{
cancellationToken.ThrowIfSourceDisposed();
// If an unstarted task has a valid CancellationToken that gets signalled while the task is still not queued
// we need to proactively cancel it, because it may never execute to transition itself.
// The only way to accomplish this is to register a callback on the CT.
// We exclude Promise tasks from this, because TaskCompletionSource needs to fully control the inner tasks's lifetime (i.e. not allow external cancellations)
if ((_internalOptions & (InternalTaskOptions.QueuedByRuntime | InternalTaskOptions.PromiseTask | InternalTaskOptions.LazyCancellation)) == 0)
{
if (cancellationToken.IsCancellationRequested)
{
// Fast path for an already-canceled cancellationToken
InternalCancel(false);
}
else
{
// Regular path for an uncanceled cancellationToken
CancellationTokenRegistration registration;
if (antecedent == null)
{
// if no antecedent was specified, use this task's reference as the cancellation state object
registration = cancellationToken.Register(_taskCancelCallback, this);
}
else
{
// If an antecedent was specified, pack this task, its antecedent and the TaskContinuation together as a tuple
// and use it as the cancellation state object. This will be unpacked in the cancellation callback so that
// antecedent.RemoveCancellation(continuation) can be invoked.
registration = cancellationToken.Register(_taskCancelCallback, new Tuple<Task, Task, TaskContinuation>(this, antecedent, continuation));
}
_cancellationRegistration = new StrongBox<CancellationTokenRegistration>(registration);
}
}
}
catch (Exception)
{
// If we have an exception related to our CancellationToken, then we need to subtract ourselves
// from our parent before throwing it.
if ((_parent != null)
&& ((_creationOptions & TaskCreationOptions.AttachedToParent) != 0)
&& ((_parent._creationOptions & TaskCreationOptions.DenyChildAttach) == 0)
)
{
_parent.DisregardChild();
}
throw;
}
}