本文整理汇总了C#中System.Threading.CancellationTokenSource.?.Cancel方法的典型用法代码示例。如果您正苦于以下问题:C# CancellationTokenSource.?.Cancel方法的具体用法?C# CancellationTokenSource.?.Cancel怎么用?C# CancellationTokenSource.?.Cancel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.CancellationTokenSource
的用法示例。
在下文中一共展示了CancellationTokenSource.?.Cancel方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
#if !DEBUG
// Check if the app is alread in the foreground and if so, don't run the agent
if (AgentSync.IsApplicationLaunched())
return;
#endif
// Get a deferral, to prevent the task from closing prematurely
// while asynchronous code is still running.
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
// Initialize the app
await Platform.Current.AppInitializingAsync(InitializationModes.Background);
Platform.Current.Logger.Log(LogLevels.Information, "Starting background task '{0}'...", taskInstance.Task.Name);
CancellationTokenSource cts = new CancellationTokenSource();
taskInstance.Canceled += (sender, reason) =>
{
Platform.Current.Logger.Log(LogLevels.Warning, "Background task '{0}' is being cancelled due to '{1}'...", taskInstance.Task.Name, reason);
// Store info on why this task was cancelled
_info.CancelReason = reason.ToString();
_info.EndTime = DateTime.UtcNow;
// Cancel/dispose the token
cts?.Cancel();
cts?.Dispose();
};
try
{
// Execute the background work
_info.StartTime = DateTime.UtcNow;
await Platform.Current.TimedBackgroundWorkAsync(BackgroundWorkCost.CurrentBackgroundWorkCost, cts.Token);
// Task ran without error
_info.RunSuccessfully = true;
Platform.Current.Logger.Log(LogLevels.Information, "Completed execution of background task '{0}'!", taskInstance.Task.Name);
}
catch(OperationCanceledException)
{
// Task was aborted via the cancelation token
Platform.Current.Logger.Log(LogLevels.Warning, "Background task '{0}' had an OperationCanceledException with reason '{1}'.", taskInstance.Task.Name, _info.CancelReason);
}
catch (Exception ex)
{
// Task threw an exception, store/log the error details
_info.ExceptionDetails = ex.ToString();
Platform.Current.Logger.LogErrorFatal(ex, "Background task '{0}' failed with exception to run to completion: {1}", taskInstance.Task.Name, ex.Message);
}
finally
{
_info.EndTime = DateTime.UtcNow;
// Store the task status information
Platform.Current.Storage.SaveSetting("TASK_" + taskInstance.Task.Name, _info, Windows.Storage.ApplicationData.Current.LocalSettings);
// Shutdown the task
Platform.Current.AppSuspending();
deferral.Complete();
}
}
示例2: CompatibleCancellationToken
/// <summary>
/// Creates a <see cref="CompatibleCancellationToken"/> based on an existing GSF cancellation token.
/// </summary>
/// <param name="token">Existing GSF token.</param>
public CompatibleCancellationToken(CancellationToken token)
{
m_source = new CancellationTokenSource();
m_token = m_source.Token;
m_sourceIsLocal = true;
token.Cancelled += (sender, e) => m_source?.Cancel();
}
示例3: ViewModelExecute
private static async Task ViewModelExecute(IExecution sender,
List<IBaseOperation> operations,
Func<Task> notifyOfActivity = null,
Func<Task> notifyActivityFinished = null,
Func<Exception, Task<bool>> handleUnhandledException = null,
Func<Task> handleTimeout = null,
int timeoutMilliseconds = 0,
IApplicationInsights insights = null,
string name = "",
object parameter = null)
{
// If currently executing, ignore the latest request
lock (sender)
{
if (!_status.ContainsKey(sender))
_status.Add(sender, true);
else if (_status[sender])
return;
else
_status[sender] = true;
}
if (sender == null)
throw new Exception($"The {nameof(IExecution)} sender can not be null");
if (notifyOfActivity == null)
throw new Exception($"{nameof(notifyOfActivity)} is null: You must notify the user that something is happening");
await notifyOfActivity();
// Background thread
var insightTask = Task.Run(() =>
{
try
{
if (insights != null)
insights.TrackEvent(name, $"User activated {name}");
}
catch (Exception ex)
{
Debug.WriteLine($"insights.TrackEvent({name}) {ex.Message}");
}
}).ConfigureAwait(false);
await Task.Run(async () =>
{
// Debug Remove Timeout
if (App.IsDebugging)
timeoutMilliseconds = 0;
sender.Result = null;
List<Func<Task>> rollbacks = new List<Func<Task>>();
bool transactionRunning = false;
// Setup Cancellation of Tasks if long running
var task = new CancellationTokenSource();
var exceptionState = new PropertyArgs() { Value = false };
if (timeoutMilliseconds > 0)
{
if (handleTimeout != null)
task.Token.Register(async (state) => { if (!(bool)((PropertyArgs)state).Value) await handleTimeout(); }, exceptionState);
else if (handleUnhandledException != null)
task.Token.Register(async (state) => { if (!(bool)((PropertyArgs)state).Value) await handleUnhandledException(new TimeoutException()); }, exceptionState);
else
throw new Exception($"You must specify either {nameof(handleTimeout)} or {nameof(handleUnhandledException)} to handle a timeout.");
task.CancelAfter(timeoutMilliseconds);
}
IList<IResult> results = new List<IResult>();
try
{
// Transaction Block
transactionRunning = true;
foreach (var operation in operations)
{
if (operation.Rollback != null)
rollbacks.Add(operation.Rollback);
if (operation is IOperation || operation is IChainedOperation)
{
var op = operation as IOperation;
if (op.Function != null)
{
try
{
await op.Function(results, parameter, task.Token);
}
catch
{
exceptionState.Value = true; // Stops registered cancel function from running, since this is exception not timeout
task?.Cancel(); // Cancel all tasks
throw; // Go to unhandled exception
}
}
//.........这里部分代码省略.........