本文整理汇总了C#中System.Threading.CancellationTokenSource.?.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# CancellationTokenSource.?.Dispose方法的具体用法?C# CancellationTokenSource.?.Dispose怎么用?C# CancellationTokenSource.?.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.CancellationTokenSource
的用法示例。
在下文中一共展示了CancellationTokenSource.?.Dispose方法的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: RefreshTiles
public async void RefreshTiles()
{
// Cancel previous loads
if (_tokenSource != null)
{
_tokenSource.Cancel();
while (_tokenSource != null)
await Task.Delay(1);
}
Spinner spinner = null;
Application.Invoke(() =>
{
// Clear controls
_buttons.Clear();
ClearTiles();
Content =
spinner = new Spinner
{
Animate = true,
MinHeight = 50,
MinWidth = 50
};
});
while (spinner == null)
await Task.Delay(5);
_buttonsPerRow = CalculateButtonsPerRow((float) Size.Width);
var i = 0;
_tokenSource = new CancellationTokenSource();
try
{
var tiles = await LoadTiles(_tokenSource.Token);
Application.Invoke(() =>
{
foreach (var tile in tiles)
{
if (tile == null) continue;
if (i >= _buttonsPerRow)
{
PushNewRow();
i = 0;
}
try
{
var button = new Button(tile.Image?.ToXwtImage()?.ScaleToSize(100))
{
Label = tile.Image == null ? tile.Text : null,
TooltipText = tile.Text,
WidthRequest = 100,
HeightRequest = 100,
MinWidth = 0,
Style = ButtonStyle.Borderless,
BackgroundColor = tile.BackgroundColor,
ImagePosition = ContentPosition.Center
};
button.Clicked += (sender, args) => tile.ClickAction();
_buttons.Add(button);
_rows.Peek().PackStart(button);
i++;
}
catch (Exception e)
{
_log.WriteLine("Failed to convert Tile object to UI");
_log.WriteException(e);
}
}
Content = _box;
});
}
catch (TaskCanceledException)
{
}
catch (OperationCanceledException)
{
}
finally
{
_tokenSource?.Dispose();
_tokenSource = null;
}
}
示例3: ViewModelExecute
//.........这里部分代码省略.........
{
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
}
}
}
else
{
var op = operation as ISingleOperation;
try
{
if (op.Function != null)
{
var resultList = await op.Function(parameter, task.Token);
if (resultList != null)
foreach (var result in resultList)
results.Add(result);
}
}
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
}
}
if (!operation.ChainedRollback)
rollbacks.Remove(operation.Rollback);
}
rollbacks.Clear();
transactionRunning = false;
// End of Transaction Block
}
catch (Exception e)
{
if (handleUnhandledException == null)
throw;
var handled = await handleUnhandledException(e);
if (!handled)
throw;
}
finally
{
try
{
task?.Dispose();
if (transactionRunning)
{
rollbacks.Reverse(); // Do rollbacks in reverse order
foreach (var rollback in rollbacks)
await rollback();
}
// Set final result
sender.Result = results;
// Handle the result
await sender.HandleResult(sender.Result);
}
finally
{
if (notifyActivityFinished == null)
throw new Exception($"{nameof(notifyActivityFinished)} is null: You need to specify what happens when the operations finish");
try
{
await notifyActivityFinished();
}
catch (Exception e)
{
var handled = await handleUnhandledException(e);
if (!handled)
throw;
}
finally
{
_status.Remove(sender);
}
}
}
});
}