Here are the examples of the csharp api System.Threading.CancellationTokenSource.Cancel(bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
587 Examples
19
Source : AppManager.cs
with MIT License
from admaiorastudio
with MIT License
from admaiorastudio
private async Task ConnectAsync()
{
if (_isConnected)
return;
// Emulators loopback addresses
IPAddress[] loopbackAddresses = new[]
{
IPAddress.Parse("127.0.0.1"),
IPAddress.Parse("10.0.2.2"),
IPAddress.Parse("10.0.3.2"),
IPAddress.Parse("169.254.80.80")
};
// Check if we are an emulator instance
List<Task<string>> waitTasks = new List<Task<string>>();
CancellationTokenSource cts = new CancellationTokenSource();
// Look for server using localhost (an emulator device)
foreach (var ipAddress in loopbackAddresses.Take(1))
{
waitTasks.Add(Task.Run<string>(
async () =>
{
try
{
bool isPortOpen = TryPing(ipAddress.ToString(), 5001, 300);
if (!isPortOpen)
return null;
var connection = new HubConnectionBuilder()
.WithUrl($"http://{ipAddress.ToString()}:5001/hub")
.Build();
await connection.StartAsync(cts.Token);
if (cts.IsCancellationRequested)
return null;
_useLocalHost = true;
_hubConnection = connection;
cts.Cancel();
return ipAddress.ToString();
}
catch (Exception ex)
{
return null;
}
}, cts.Token));
}
// Look for server using broadcast (a real device)
waitTasks.Add(Task.Run<string>(
async () =>
{
// Discover the server
using (UdpClient client = new UdpClient())
{
client.EnableBroadcast = true;
byte[] requestData = Encoding.ASCII.GetBytes($"AreYouTheServer?");
Task<int> sendTask = client.SendAsync(requestData, requestData.Length, new IPEndPoint(IPAddress.Broadcast, 5002));
await Task.WhenAny(new[] { sendTask, Task.Delay(300) });
if (sendTask.IsCompleted)
{
if (cts.IsCancellationRequested)
return null;
Task<UdpReceiveResult> receiveTask = client.ReceiveAsync();
await Task.WhenAny(new[] { receiveTask, Task.Delay(300) });
if (receiveTask.IsCompleted)
{
if (cts.IsCancellationRequested)
return null;
UdpReceiveResult serverResponseData = receiveTask.Result;
string serverResponse = Encoding.ASCII.GetString(serverResponseData.Buffer);
if (serverResponse == "YesIamTheServer!")
{
string ipAddress = serverResponseData.RemoteEndPoint.Address.ToString();
_useLocalHost = false;
_hubConnection = null;
cts.Cancel();
return ipAddress.ToString();
}
}
}
client.Close();
}
return null;
}));
// Timeout task
waitTasks.Add(Task.Run<string>(
async () =>
{
try
{
await Task.Delay(5000, cts.Token);
cts.Cancel();
return null;
}
catch
{
return null;
}
}));
try
{
string ipAddress = await WaitForAnyGetHostIpTaskAsync(waitTasks);
if (ipAddress != null)
{
if (_hubConnection == null)
{
string port = _useLocalHost ? "5001" : "5002";
_hubConnection = new HubConnectionBuilder()
.WithUrl($"http://{ipAddress.ToString()}:{port}/hub")
.Build();
await _hubConnection.StartAsync();
}
_isConnected = true;
_serverAddress = ipAddress;
_hubConnection.Closed +=
async (error) =>
{
System.Diagnostics.Debug.WriteLine("Connection with RealXaml has been lost.");
while(_hubConnection.State == HubConnectionState.Disconnected)
{
bool isPortOpen = TryPing(ipAddress.ToString(), 5001, 300);
if (isPortOpen)
{
System.Diagnostics.Debug.WriteLine("Trying to reconnect again...");
await _hubConnection.StartAsync();
if (_hubConnection.State == HubConnectionState.Connected)
{
await Task.Delay(300);
await _hubConnection.SendAsync("NotifyIde", "Connection was lost. Here I'am again.");
System.Diagnostics.Debug.WriteLine($"Successfully restored lost to the RealXaml server.");
break;
}
}
System.Diagnostics.Debug.WriteLine("Unable to connect. Retrying in 5secs.");
await Task.Delay(5000);
}
};
_hubConnection.On<string, byte[], bool>("ReloadXaml",
async (pageId, data, refresh) => await WhenReloadXaml(pageId, data, refresh));
_hubConnection.On<string, byte[]>("Reloadreplacedembly",
async (replacedemblyName, data) => await WhenReloadreplacedembly(replacedemblyName, data));
string clientId = $"RXID-{DateTime.Now.Ticks}";
await _hubConnection.SendAsync("RegisterClient", clientId);
System.Diagnostics.Debug.WriteLine($"Successfully connected to the RealXaml server.");
System.Diagnostics.Debug.WriteLine($"Your client ID is {clientId}");
return;
}
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error while trying to connect to the RealXaml server.");
System.Diagnostics.Debug.WriteLine(ex);
}
}
19
Source : ViewerServer.cs
with MIT License
from admaiorastudio
with MIT License
from admaiorastudio
private void Dispose(bool disposing)
{
if(!_disposed && disposing)
{
_cts?.Cancel();
}
_disposed = true;
}
19
Source : Program.cs
with MIT License
from alsami
with MIT License
from alsami
public static async Task Main(string[] _)
{
var ctx = new CancellationToken();
var ctxs = CancellationTokenSource.CreateLinkedTokenSource(ctx);
Console.CancelKeyPress += (x, y) =>
{
y.Cancel = true;
ctxs.Cancel(false);
};
var builder = new ContainerBuilder();
builder.RegisterMediatR(typeof(CustomerLoadQuery).replacedembly);
builder.RegisterType<CustomersRepository>()
.As<ICustomersRepository>()
.SingleInstance();
var container = builder.Build();
var lifetimeScope = container.Resolve<ILifetimeScope>();
var googleCustomerAddCommand = new CustomerAddCommand(Guid.NewGuid(), "google");
await using (var scope = lifetimeScope.BeginLifetimeScope())
{
var mediator = scope.Resolve<IMediator>();
await mediator.Send(googleCustomerAddCommand, ctx);
}
await using (var scope = lifetimeScope.BeginLifetimeScope())
{
var mediator = scope.Resolve<IMediator>();
var customer = await mediator.Send(new CustomerLoadQuery(googleCustomerAddCommand.Id), ctx);
Console.WriteLine(googleCustomerAddCommand.Name == customer.Name);
try
{
await mediator.Send(new CustomerLoadQuery(Guid.Empty), ctx);
}
catch (CustomerNotFoundException)
{
Console.WriteLine("Expected that the customer could not be found bc we didn't add him b4.");
}
}
Console.ReadKey();
}
19
Source : Cheese.cs
with MIT License
from altskop
with MIT License
from altskop
public static void ObserveShipStatus(System.Action<uint> onChangeShipStatus)
{
CancellationTokenSource cts = new CancellationTokenSource();
if (Tokens.ContainsKey("ObserveShipStatus"))
{
Tokens["ObserveShipStatus"].Cancel();
Tokens.Remove("ObserveShipStatus");
}
Tokens.Add("ObserveShipStatus", cts);
Cheese.onChangeShipStatus = onChangeShipStatus;
Task.Factory.StartNew(_ObserveShipStatus, cts.Token);
}
19
Source : PlayerData.cs
with MIT License
from altskop
with MIT License
from altskop
public void StopObserveState()
{
var key = Tokens.ContainsKey("ObserveState");
if(key)
{
if (Tokens["ObserveState"].IsCancellationRequested == false)
{
Tokens["ObserveState"].Cancel();
Tokens.Remove("ObserveState");
}
}
}
19
Source : FilePlotterUC.cs
with MIT License
from Analogy-LogViewer
with MIT License
from Analogy-LogViewer
private void SetupEventHandlers()
{
dockManager1.StartDocking += (s, e) =>
{
if (e.Panel.DockedAsTabbedDoreplacedent)
{
var sz = e.Panel.Size;
BeginInvoke(new Action(() =>
{
e.Panel.FloatSize = sz;
//adjust the new panel size taking the header height into account:
e.Panel.FloatSize = new Size(e.Panel.FloatSize.Width, 2 * e.Panel.FloatSize.Height - e.Panel.ControlContainer.Height);
}));
}
else
{
e.Panel.FloatSize = e.Panel.Size;
}
};
sbtnBrowse.Click += (_, __) =>
{
using OpenFileDialog openFileDialog1 = new OpenFileDialog
{
replacedle = @"Open Files",
Multiselect = false
};
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
teFile.Text = openFileDialog1.FileName;
}
};
sbtnLoad.Click += (_, __) =>
{
void Cancel()
{
sbtnLoad.Text = "load";
InFileProcess = false;
}
if (!string.IsNullOrEmpty(teFile.Text) && File.Exists(teFile.Text))
{
if (InFileProcess)
{
cts.Cancel(false);
return;
}
InFileProcess = true;
sbtnLoad.Text = "Cancel";
cts = new CancellationTokenSource();
var token = cts.Token;
token.Register(Cancel, true);
string fileName = teFile.Text;
bool firstRowIsreplacedle = ceFirstRowreplacedle.Checked;
bool customXAxis = ceFirstCulmnIsXAxis.Checked;
replacedogyCustomXAxisPlot xAxisType = replacedogyCustomXAxisPlot.Numerical;
if (customXAxis)
{
if (rgFirstColumnType.SelectedIndex == 0)
{
xAxisType = replacedogyCustomXAxisPlot.DateTimeUnixMillisecond;
}
else if (rgFirstColumnType.SelectedIndex == 1)
{
xAxisType = replacedogyCustomXAxisPlot.DateTimeUnixSecond;
}
else if (rgFirstColumnType.SelectedIndex == 2)
{
xAxisType = replacedogyCustomXAxisPlot.Numerical;
}
}
replacedogyFilePlotting afp = new replacedogyFilePlotting(fileName, firstRowIsreplacedle, customXAxis, xAxisType, token);
var interactor = new replacedogyPlottingInteractor();
DataPlotterUC uc = new DataPlotterUC(afp, interactor);
//add panel
var page = dockManager1.AddPanel(DockingStyle.Float);
page.DockedAsTabbedDoreplacedent = true;
page.Controls.Add(uc);
uc.Dock = DockStyle.Fill;
page.Text = fileName;
dockManager1.ActivePanel = page;
uc.Start();
processTask = afp.StartPlotting();
}
};
}
19
Source : LogService.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
public byte[] Read()
{
_readStarted = true;
_writeCTS.Cancel(false);
var data = new List<byte>();
var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
try
{
lock (this)
{
if (Directory.Exists(folderPath))
{
var filePath = Path.Combine(folderPath, FILE_NAME);
if (File.Exists(filePath))
{
var fStream = File.OpenRead(filePath);
var buffer = new byte[4 * 1024];
while (fStream.Read(buffer, 0, buffer.Length) > 0)
{
data.AddRange(buffer);
}
fStream.Close();
File.Delete(filePath);
_cachedLogBytes = new List<byte>();
}
}
}
}
catch
{ }
_readStarted = false;
return data.ToArray();
}
19
Source : BaseCollectionFiVm.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
protected Task BuildSelectedValue()
{
if (CTS != null)
CTS.Cancel(false);
CTS = new CancellationTokenSource();
return Task.Run(() =>
{
SelectedValue = new ApplyedFilter
{
Id = this.Id,
DataType = this.DataType,
Values = Items.Where(x => x.Selected).Select(y => new ApplyedFilterValue { Id = y.Id }).ToList()
};
}, CTS.Token);
}
19
Source : FilterSelectionViewModel.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
private Task BuildSelectedValues()
{
if (CTS != null)
CTS.Cancel(false);
CTS = new CancellationTokenSource();
return Task.Run(() =>
{
SelectedValues = Items.Where(x => x.Selected).Select(y => new ApplyedFilterValue { Id = y.Id }).ToList();
}, CTS.Token);
}
19
Source : PickerFiVm.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
protected Task BuildSelectedValue(PickerCollectionItemVM item)
{
if (CTS != null)
CTS.Cancel(false);
CTS = new CancellationTokenSource();
return Task.Run(() =>
{
SelectedValue = new ApplyedFilter
{
Id = this.Id,
DataType = this.DataType,
Values = new List<ApplyedFilterValue> { new ApplyedFilterValue { Id = item.Id } }
};
}, CTS.Token);
}
19
Source : LogService.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
public byte[] Read()
{
_readStarted = true;
_writeCTS.Cancel(false);
var data = new List<byte>();
var doreplacedents = Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents);
var folderPath = Path.Combine(doreplacedents, _folderName);
try
{
lock (this)
{
if (Directory.Exists(folderPath))
{
var filePath = Path.Combine(folderPath, FILE_NAME);
if (File.Exists(filePath))
{
var fStream = File.OpenRead(filePath);
var buffer = new byte[4 * 1024];
while (fStream.Read(buffer, 0, buffer.Length) > 0)
{
data.AddRange(buffer);
}
fStream.Close();
File.Delete(filePath);
lock (_cachedLogBytes)
{
_cachedLogBytes = new List<byte>();
}
}
}
}
}
catch
{ }
_readStarted = false;
return data.ToArray();
}
19
Source : PickerPciVm.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
protected Task BuildSelectedValue(PickerCollectionItemVM item)
{
if (CTS != null)
CTS.Cancel(false);
CTS = new CancellationTokenSource();
return Task.Run(() =>
{
SelectedValue = new ApplyedProductParameter
{
Id = this.Id,
DataType = this.DataType,
Values = new List<ApplyedProductParameterValue> { new ApplyedProductParameterValue { Id = item.Id } }
};
}, CTS.Token);
}
19
Source : ProductDetailsSelectionViewModel.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
private Task BuildSelectedValues()
{
if (CTS != null)
CTS.Cancel(false);
CTS = new CancellationTokenSource();
return Task.Run(() =>
{
SelectedValues = Items.Where(x => x.Selected).Select(y => new ApplyedProductParameterValue { Id = y.Id }).ToList();
}, CTS.Token);
}
19
Source : AsyncQueueDispatcher.cs
with MIT License
from AspectCore
with MIT License
from AspectCore
public void Stop()
{
_cancellationTokenSource.Cancel(throwOnFirstException: false);
_processQueueTask?.Wait(_timeoutOnStopMs);
_logger?.LogInformation($"Stop {Name}.");
_status = false;
}
19
Source : OwinWebSocketWrapper.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
internal void Cancel()
{
try
{
_cancellationTokenSource.Cancel(throwOnFirstException: false);
}
catch (ObjectDisposedException)
{
}
catch (AggregateException ex)
{
_trace.WriteError(Resources.Trace_WebSocketException, ex);
}
}
19
Source : HostingEngine.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
private static IDisposable EnableDisposing(StartContext context)
{
var cts = new CancellationTokenSource();
context.Builder.Properties[Constants.HostOnAppDisposing] = cts.Token;
context.EnvironmentData.Add(new KeyValuePair<string, object>(Constants.HostOnAppDisposing, cts.Token));
return new Disposable(() => cts.Cancel(false));
}
19
Source : ShutdownDetector.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
private void Cancel()
{
// Stop the timer as we don't need it anymore
if (_checkAppPoolTimer != null)
{
_checkAppPoolTimer.Dispose();
}
// Trigger the cancellation token
try
{
_cts.Cancel(throwOnFirstException: false);
}
catch (ObjectDisposedException)
{
}
catch (AggregateException ag)
{
_trace.WriteError(Resources.Trace_ShutdownException, ag);
}
}
19
Source : DisconnectWatcher.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
private static void SetDisconnected(object obj)
{
var context = (Disconnecreplacedcher)obj;
CancellationTokenSource cts = context._callCancelledSource;
if (cts == null)
{
return;
}
try
{
cts.Cancel(throwOnFirstException: false);
}
catch (ObjectDisposedException)
{
}
catch (AggregateException ag)
{
Trace.WriteError(Resources.Trace_RequestDisconnectCallbackExceptions, ag);
}
}
19
Source : TestBase.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_disposing.Cancel(false);
_disposing.Dispose();
}
}
19
Source : SSEMailboxHandler.cs
with MIT License
from azist
with MIT License
from azist
protected override void Destructor()
{
try { m_CancelSource.Cancel(true); } catch{ /* canceling task.Delay() - nothing to log */ }
m_Mailboxes.ForEach(kvp => this.DontLeak(() => CloseMailbox(kvp.Value), errorFrom: "dctor.CloseMailbox()"));
m_CancelSource.Dispose();
base.Destructor();
}
19
Source : KustoHeartBeatService.cs
with MIT License
from Azure
with MIT License
from Azure
public void Dispose()
{
DiagnosticsETWProvider.Instance.LogRuntimeHostMessage("Disposing KustoHeartBeatService");
_cancellationToken.Cancel();
}
19
Source : Program.cs
with MIT License
from Azure
with MIT License
from Azure
static void Main(string[] args)
{
Configure();
var cts = new CancellationTokenSource();
_ = Run(cts.Token);
// Finish on key press
Console.ReadKey();
cts.Cancel();
}
19
Source : TaskExtensions.cs
with MIT License
from Azure
with MIT License
from Azure
public static async Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout,
[CallerFilePath] string filePath = null,
[CallerLineNumber] int lineNumber = default)
{
// Don't create a timer if the task is already completed
// or the debugger is attached
if (task.IsCompleted || Debugger.IsAttached)
{
return await task;
}
var cts = new CancellationTokenSource();
if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)))
{
cts.Cancel();
return await task;
}
else
{
throw new TimeoutException(CreateMessage(timeout, filePath, lineNumber));
}
}
19
Source : TaskExtensions.cs
with MIT License
from Azure
with MIT License
from Azure
public static async Task TimeoutAfter(this Task task, TimeSpan timeout,
[CallerFilePath] string filePath = null,
[CallerLineNumber] int lineNumber = default)
{
// Don't create a timer if the task is already completed
// or the debugger is attached
if (task.IsCompleted || Debugger.IsAttached)
{
await task;
return;
}
var cts = new CancellationTokenSource();
if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)))
{
cts.Cancel();
await task;
}
else
{
throw new TimeoutException(CreateMessage(timeout, filePath, lineNumber));
}
}
19
Source : ChangeFeedEstimatorRunner.cs
with MIT License
from Azure
with MIT License
from Azure
public override async Task StopAsync()
{
DefaultTrace.TraceInformation("Stopping estimator...");
if (this.running)
{
this.shutdownCts.Cancel();
try
{
await this.runAsync.ConfigureAwait(false);
}
catch (OperationCanceledException ex)
{
// Expected during shutdown
Extensions.TraceException(ex);
}
this.running = false;
}
}
19
Source : TokenCredentialCache.cs
with MIT License
from Azure
with MIT License
from Azure
public void Dispose()
{
if (this.isDisposed)
{
return;
}
this.cancellationTokenSource.Cancel();
this.cancellationTokenSource.Dispose();
this.isDisposed = true;
}
19
Source : BatchAsyncStreamer.cs
with MIT License
from Azure
with MIT License
from Azure
public void Dispose()
{
this.cancellationTokenSource.Cancel();
this.cancellationTokenSource.Dispose();
this.currentTimer.CancelTimer();
this.currentTimer = null;
this.timerTask = null;
if (this.congestionControlTimer != null)
{
this.congestionControlTimer.CancelTimer();
this.congestionControlTimer = null;
this.congestionControlTask = null;
}
}
19
Source : PartitionControllerCore.cs
with MIT License
from Azure
with MIT License
from Azure
public override async Task ShutdownAsync()
{
this.shutdownCts.Cancel();
IEnumerable<Task> leases = this.currentlyOwnedParreplacedions.Select(pair => pair.Value.Task).ToList();
await Task.WhenAll(leases).ConfigureAwait(false);
}
19
Source : PartitionLoadBalancerCore.cs
with MIT License
from Azure
with MIT License
from Azure
public override async Task StopAsync()
{
if (this.runTask == null)
{
throw new InvalidOperationException("Start has to be called before stop");
}
this.cancellationTokenSource.Cancel();
await this.runTask.ConfigureAwait(false);
}
19
Source : PartitionSupervisorCore.cs
with MIT License
from Azure
with MIT License
from Azure
public override async Task RunAsync(CancellationToken shutdownToken)
{
await this.observer.OpenAsync(this.lease.CurrentLeaseToken).ConfigureAwait(false);
this.processorCancellation = CancellationTokenSource.CreateLinkedTokenSource(shutdownToken);
Task processorTask = this.processor.RunAsync(this.processorCancellation.Token);
processorTask.ContinueWith(_ => this.renewerCancellation.Cancel()).LogException();
Task renewerTask = this.renewer.RunAsync(this.renewerCancellation.Token);
renewerTask.ContinueWith(_ => this.processorCancellation.Cancel()).LogException();
ChangeFeedObserverCloseReason closeReason = shutdownToken.IsCancellationRequested ?
ChangeFeedObserverCloseReason.Shutdown :
ChangeFeedObserverCloseReason.Unknown;
try
{
await Task.WhenAll(processorTask, renewerTask).ConfigureAwait(false);
}
catch (LeaseLostException)
{
closeReason = ChangeFeedObserverCloseReason.LeaseLost;
throw;
}
catch (FeedRangeGoneException)
{
closeReason = ChangeFeedObserverCloseReason.LeaseGone;
throw;
}
catch (CosmosException)
{
closeReason = ChangeFeedObserverCloseReason.CosmosException;
throw;
}
catch (OperationCanceledException) when (shutdownToken.IsCancellationRequested)
{
closeReason = ChangeFeedObserverCloseReason.Shutdown;
}
catch (ChangeFeedProcessorUserException)
{
closeReason = ChangeFeedObserverCloseReason.ObserverError;
throw;
}
catch (Exception) when (processorTask.IsFaulted)
{
closeReason = ChangeFeedObserverCloseReason.Unknown;
throw;
}
finally
{
await this.observer.CloseAsync(this.lease.CurrentLeaseToken, closeReason).ConfigureAwait(false);
}
}
19
Source : GlobalEndpointManager.cs
with MIT License
from Azure
with MIT License
from Azure
private async Task GetAndUpdateAccountPropertiesAsync(Uri endpoint)
{
try
{
if (this.CancellationTokenSource.IsCancellationRequested)
{
lock (this.TransientExceptions)
{
this.TransientExceptions.Add(new OperationCanceledException("GlobalEndpointManager: Get account information canceled"));
}
return;
}
AccountProperties databaseAccount = await this.GetDatabaseAccountFn(endpoint);
if (databaseAccount != null)
{
this.AccountProperties = databaseAccount;
this.CancellationTokenSource.Cancel();
}
}
catch (Exception e)
{
DefaultTrace.TraceInformation("GlobalEndpointManager: Fail to reach gateway endpoint {0}, {1}", endpoint, e.ToString());
if (GetAccountPropertiesHelper.IsNonRetriableException(e))
{
DefaultTrace.TraceInformation("GlobalEndpointManager: Exception is not retriable");
this.CancellationTokenSource.Cancel();
this.NonRetriableException = e;
}
else
{
lock (this.TransientExceptions)
{
this.TransientExceptions.Add(e);
}
}
}
}
19
Source : GlobalEndpointManager.cs
with MIT License
from Azure
with MIT License
from Azure
public void Dispose()
{
this.connectionPolicy.PreferenceChanged -= this.OnPreferenceChanged;
if (!this.cancellationTokenSource.IsCancellationRequested)
{
// This can cause task canceled exceptions if the user disposes of the object while awaiting an async call.
this.cancellationTokenSource.Cancel();
// The background timer task can hit a ObjectDisposedException but it's an async background task
// that is never awaited on so it will not be thrown back to the caller.
this.cancellationTokenSource.Dispose();
}
}
19
Source : ChangeFeedIteratorCoreTests.cs
with MIT License
from Azure
with MIT License
from Azure
[TestMethod]
public async Task TestCancellationTokenAsync()
{
CancellationTokenRequestHandler cancellationTokenHandler = new CancellationTokenRequestHandler();
ContainerInternal itemsCore = await this.InitializeContainerAsync();
await this.CreateRandomItems(itemsCore, 100, randomParreplacedionKey: true);
// Inject validating handler
RequestHandler currentInnerHandler = this.cosmosClient.RequestHandler.InnerHandler;
this.cosmosClient.RequestHandler.InnerHandler = cancellationTokenHandler;
cancellationTokenHandler.InnerHandler = currentInnerHandler;
{
// Test to see if the token flows to the pipeline
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
ChangeFeedIteratorCore feedIterator = itemsCore.GetChangeFeedStreamIterator(
ChangeFeedStartFrom.Beginning(),
ChangeFeedMode.Incremental) as ChangeFeedIteratorCore;
await feedIterator.ReadNextAsync(cancellationTokenSource.Token);
replacedert.AreEqual(cancellationTokenSource.Token, cancellationTokenHandler.LastUsedToken, "The token preplaceded did not reach the pipeline");
}
// See if cancellation token is honored for first request
try
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.Cancel();
ChangeFeedIteratorCore feedIterator = itemsCore.GetChangeFeedStreamIterator(
ChangeFeedStartFrom.Beginning(),
ChangeFeedMode.Incremental) as ChangeFeedIteratorCore;
await feedIterator.ReadNextAsync(cancellationTokenSource.Token);
replacedert.Fail("Expected exception.");
}
catch (OperationCanceledException)
{
}
// See if cancellation token is honored for second request
try
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.Cancel();
ChangeFeedIteratorCore feedIterator = itemsCore.GetChangeFeedStreamIterator(
ChangeFeedStartFrom.Beginning(),
ChangeFeedMode.Incremental) as ChangeFeedIteratorCore;
await feedIterator.ReadNextAsync();
await feedIterator.ReadNextAsync(cancellationTokenSource.Token);
replacedert.Fail("Expected exception.");
}
catch (OperationCanceledException)
{
}
// See if cancellation token is honored mid draining
try
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
ChangeFeedIteratorCore feedIterator = itemsCore.GetChangeFeedStreamIterator(
ChangeFeedStartFrom.Beginning(),
ChangeFeedMode.Incremental) as ChangeFeedIteratorCore;
await feedIterator.ReadNextAsync(cancellationTokenSource.Token);
cancellationTokenSource.Cancel();
await feedIterator.ReadNextAsync(cancellationTokenSource.Token);
replacedert.Fail("Expected exception.");
}
catch (OperationCanceledException)
{
}
}
19
Source : AsyncCacheNonBlocking.cs
with MIT License
from Azure
with MIT License
from Azure
private void Dispose(bool disposing)
{
if (this.isDisposed)
{
return;
}
if (disposing)
{
try
{
this.cancellationTokenSource.Cancel();
this.cancellationTokenSource.Dispose();
}
catch (ObjectDisposedException exception)
{
// Need to access the exception to avoid unobserved exception
DefaultTrace.TraceInformation($"AsyncCacheNonBlocking was already disposed: {0}", exception);
}
this.isDisposed = true;
}
}
19
Source : ClientTelemetry.cs
with MIT License
from Azure
with MIT License
from Azure
public void Dispose()
{
this.cancellationTokenSource.Cancel();
this.cancellationTokenSource.Dispose();
this.telemetryTask = null;
}
19
Source : ChangeFeedAsyncEnumerableTests.cs
with MIT License
from Azure
with MIT License
from Azure
[TestMethod]
[ExpectedException(typeof(OperationCanceledException))]
public async Task TestCancellationToken()
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.Cancel();
IAsyncEnumerable<TryCatch<ChangeFeedPage>> asyncEnumerable = this.Container.GetChangeFeedAsyncEnumerable(
ChangeFeedCrossFeedRangeState.CreateFromBeginning(),
ChangeFeedMode.Incremental);
await foreach (TryCatch<ChangeFeedPage> monadicPage in asyncEnumerable.WithCancellation(cancellationTokenSource.Token))
{
monadicPage.ThrowIfFailed();
}
}
19
Source : ReadFeedAsyncEnumerableTests.cs
with MIT License
from Azure
with MIT License
from Azure
[TestMethod]
[ExpectedException(typeof(OperationCanceledException))]
public async Task TestCancellationToken()
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.Cancel();
IAsyncEnumerable<TryCatch<ReadFeedPage>> asyncEnumerable = this.Container.GetReadFeedAsyncEnumerable(
ReadFeedCrossFeedRangeState.CreateFromBeginning());
await foreach (TryCatch<ReadFeedPage> monadicPage in asyncEnumerable.WithCancellation(cancellationTokenSource.Token))
{
monadicPage.ThrowIfFailed();
}
}
19
Source : CosmosOperationCanceledExceptionTests.cs
with MIT License
from Azure
with MIT License
from Azure
[TestMethod]
public async Task CheckCancellationTokenGatewayTestAsync()
{
using (CosmosClient gatewayClient = TestCommon.CreateCosmosClient(
builder => builder.WithConnectionModeGateway()))
{
Container gatewayContainer = gatewayClient.GetContainer(this.database.Id, this.Container.Id);
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.Cancel();
await this.CheckCancellationTokenTestAsync(gatewayContainer, cancellationTokenSource.Token);
}
}
19
Source : CosmosOperationCanceledExceptionTests.cs
with MIT License
from Azure
with MIT License
from Azure
[TestMethod]
public async Task CheckCancellationWithTransportIntercepterTestAsync()
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
Container withCancellationToken = TransportClientHelper.GetContainerWithIntercepter(
this.database.Id,
this.Container.Id,
(uri, resourceOperation, doreplacedentServiceRequest) =>
{
if (doreplacedentServiceRequest.ResourceType == Doreplacedents.ResourceType.Doreplacedent)
{
cancellationTokenSource.Cancel();
}
},
useGatewayMode: false,
(uri, resourceOperation, doreplacedentServiceRequest)
=> TransportClientHelper.ReturnThrottledStoreResponseOnItemOperation(uri, resourceOperation, doreplacedentServiceRequest, Guid.NewGuid(), string.Empty));
await this.CheckCancellationTokenTestAsync(withCancellationToken, cancellationTokenSource.Token);
}
19
Source : CosmosOperationCanceledExceptionTests.cs
with MIT License
from Azure
with MIT License
from Azure
[TestMethod]
public async Task CheckCancellationTokenDirectTestAsync()
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.Cancel();
await this.CheckCancellationTokenTestAsync(this.Container, cancellationTokenSource.Token);
}
19
Source : ReadManyQueryHelper.cs
with MIT License
from Azure
with MIT License
from Azure
private void CancelCancellationToken(CancellationToken cancellationToken)
{
using (CancellationTokenSource cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
cancellationTokenSource.Cancel();
}
}
19
Source : BaseCosmosClientHelper.cs
with MIT License
from Azure
with MIT License
from Azure
public async Task TestCleanup()
{
if (this.cosmosClient == null)
{
return;
}
if (this.database != null)
{
await this.database.DeleteStreamAsync(
requestOptions: null,
cancellationToken: this.cancellationToken);
}
this.cancellationTokenSource?.Cancel();
this.cosmosClient.Dispose();
}
19
Source : CosmosDatabaseTests.cs
with MIT License
from Azure
with MIT License
from Azure
[TestCleanup]
public void TestCleanup()
{
if (this.cosmosClient == null)
{
return;
}
this.cancellationTokenSource?.Cancel();
this.cosmosClient.Dispose();
}
19
Source : CosmosSpatialTests.cs
with MIT License
from Azure
with MIT License
from Azure
[TestCleanup]
public async Task Cleanup()
{
if (this.doreplacedentClient != null)
{
this.doreplacedentClient.Dispose();
}
if (this.cosmosClient == null)
{
return;
}
if (this.database != null)
{
await this.database.DeleteStreamAsync(
requestOptions: null,
cancellationToken: this.cancellationToken);
}
this.cancellationTokenSource?.Cancel();
this.cosmosClient.Dispose();
}
19
Source : PartitionSupervisorTests.cs
with MIT License
from Azure
with MIT License
from Azure
[TestMethod]
public async Task RunObserver_ShouldCancelTasks_WhenTokenCanceled()
{
Task renewerTask = Task.FromResult(false);
Mock.Get(this.leaseRenewer)
.Setup(renewer => renewer.RunAsync(It.IsAny<CancellationToken>()))
.Returns<CancellationToken>(token => renewerTask = Task.Delay(TimeSpan.FromMinutes(1), token));
Task processorTask = Task.FromResult(false);
Mock.Get(this.parreplacedionProcessor)
.Setup(processor => processor.RunAsync(It.IsAny<CancellationToken>()))
.Returns<CancellationToken>(token => processorTask = Task.Delay(TimeSpan.FromMinutes(1), token));
Task supervisorTask = this.sut.RunAsync(this.shutdownToken.Token);
Task delay = Task.Delay(TimeSpan.FromMilliseconds(100));
Task finished = await Task.WhenAny(supervisorTask, delay).ConfigureAwait(false);
replacedert.AreEqual(delay, finished);
this.shutdownToken.Cancel();
await supervisorTask.ConfigureAwait(false);
replacedert.IsTrue(renewerTask.IsCanceled);
replacedert.IsTrue(processorTask.IsCanceled);
Mock.Get(this.parreplacedionProcessor)
.Verify(processor => processor.RunAsync(It.IsAny<CancellationToken>()), Times.Once);
Mock.Get(this.observer)
.Verify(feedObserver => feedObserver
.CloseAsync(It.Is<string>(lt => lt == this.lease.CurrentLeaseToken),
ChangeFeedObserverCloseReason.Shutdown));
}
19
Source : PartitionSupervisorTests.cs
with MIT License
from Azure
with MIT License
from Azure
[TestMethod]
public async Task RunObserver_ShouldPreplacedParreplacedionToObserver_WhenExecuted()
{
Mock.Get(this.observer)
.Setup(feedObserver => feedObserver.ProcessChangesAsync(It.IsAny<ChangeFeedObserverContextCore>(), It.IsAny<Stream>(), It.IsAny<CancellationToken>()))
.Callback(() => this.shutdownToken.Cancel());
await this.sut.RunAsync(this.shutdownToken.Token).ConfigureAwait(false);
Mock.Get(this.observer)
.Verify(feedObserver => feedObserver
.OpenAsync(It.Is<string>(lt => lt == this.lease.CurrentLeaseToken)));
}
19
Source : FeedEstimatorRunnerTests.cs
with MIT License
from Azure
with MIT License
from Azure
[TestMethod]
public async Task FeedEstimatorRunner_ReceivesEstimation()
{
const long estimation = 10;
bool detectedEstimationCorrectly = false;
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(500);
Task estimatorDispatcher(long detectedEstimation, CancellationToken token)
{
detectedEstimationCorrectly = estimation == detectedEstimation;
cancellationTokenSource.Cancel();
return Task.CompletedTask;
}
Mock<FeedResponse<ChangeFeedProcessorState>> mockedResponse = new Mock<FeedResponse<ChangeFeedProcessorState>>();
mockedResponse.Setup(r => r.Count).Returns(1);
mockedResponse.Setup(r => r.GetEnumerator()).Returns(new List<ChangeFeedProcessorState>() { new ChangeFeedProcessorState(string.Empty, estimation, string.Empty) }.GetEnumerator());
Mock<FeedIterator<ChangeFeedProcessorState>> mockedIterator = new Mock<FeedIterator<ChangeFeedProcessorState>>();
mockedIterator.Setup(i => i.ReadNextAsync(It.IsAny<CancellationToken>())).ReturnsAsync(mockedResponse.Object);
Mock<ChangeFeedEstimator> mockedEstimator = new Mock<ChangeFeedEstimator>();
mockedEstimator.Setup(e => e.GetCurrentStateIterator(It.IsAny<ChangeFeedEstimatorRequestOptions>())).Returns(mockedIterator.Object);
FeedEstimatorRunner estimatorCore = new FeedEstimatorRunner(estimatorDispatcher, mockedEstimator.Object, Mock.Of<ChangeFeedProcessorHealthMonitor>(), TimeSpan.FromMilliseconds(10));
try
{
await estimatorCore.RunAsync(cancellationTokenSource.Token);
}
catch (TaskCanceledException)
{
// expected
}
replacedert.IsTrue(detectedEstimationCorrectly);
}
19
Source : FeedEstimatorRunnerTests.cs
with MIT License
from Azure
with MIT License
from Azure
[TestMethod]
public async Task FeedEstimatorRunner_TransientErrorsShouldContinue()
{
const long estimation = 10;
bool detectedEstimationCorrectly = false;
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(500);
Task estimatorDispatcher(long detectedEstimation, CancellationToken token)
{
detectedEstimationCorrectly = estimation == detectedEstimation;
cancellationTokenSource.Cancel();
return Task.CompletedTask;
}
Mock<FeedResponse<ChangeFeedProcessorState>> mockedResponse = new Mock<FeedResponse<ChangeFeedProcessorState>>();
mockedResponse.Setup(r => r.Count).Returns(1);
mockedResponse.Setup(r => r.GetEnumerator()).Returns(new List<ChangeFeedProcessorState>() { new ChangeFeedProcessorState(string.Empty, estimation, string.Empty) }.GetEnumerator());
CosmosException exception = CosmosExceptionFactory.CreateThrottledException("throttled", new Headers());
Mock<FeedIterator<ChangeFeedProcessorState>> mockedIterator = new Mock<FeedIterator<ChangeFeedProcessorState>>();
mockedIterator.SetupSequence(i => i.ReadNextAsync(It.IsAny<CancellationToken>()))
.ThrowsAsync(exception)
.ReturnsAsync(mockedResponse.Object);
Mock<ChangeFeedEstimator> mockedEstimator = new Mock<ChangeFeedEstimator>();
mockedEstimator.Setup(e => e.GetCurrentStateIterator(It.IsAny<ChangeFeedEstimatorRequestOptions>())).Returns(mockedIterator.Object);
Mock<ChangeFeedProcessorHealthMonitor> healthMonitor = new Mock<ChangeFeedProcessorHealthMonitor>();
FeedEstimatorRunner estimatorCore = new FeedEstimatorRunner(estimatorDispatcher, mockedEstimator.Object, healthMonitor.Object, TimeSpan.FromMilliseconds(10));
try
{
await estimatorCore.RunAsync(cancellationTokenSource.Token);
}
catch (TaskCanceledException)
{
// expected
}
replacedert.IsTrue(detectedEstimationCorrectly);
mockedIterator.Verify(i => i.ReadNextAsync(It.IsAny<CancellationToken>()), Times.Exactly(2));
healthMonitor
.Verify(m => m.NotifyErrorAsync(It.IsAny<string>(), exception), Times.Once);
}
19
Source : FeedEstimatorRunnerTests.cs
with MIT License
from Azure
with MIT License
from Azure
[TestMethod]
public async Task FeedEstimatorRunner_NoLeases()
{
const long estimation = 1; // When no leases the expected behavior is that the estimation is 1
bool detectedEstimationCorrectly = false;
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(500);
Task estimatorDispatcher(long detectedEstimation, CancellationToken token)
{
detectedEstimationCorrectly = estimation == detectedEstimation;
cancellationTokenSource.Cancel();
return Task.CompletedTask;
}
Mock<FeedResponse<ChangeFeedProcessorState>> mockedResponse = new Mock<FeedResponse<ChangeFeedProcessorState>>();
mockedResponse.Setup(r => r.Count).Returns(0);
Mock<FeedIterator<ChangeFeedProcessorState>> mockedIterator = new Mock<FeedIterator<ChangeFeedProcessorState>>();
mockedIterator.Setup(i => i.ReadNextAsync(It.IsAny<CancellationToken>())).ReturnsAsync(mockedResponse.Object);
Mock<ChangeFeedEstimator> mockedEstimator = new Mock<ChangeFeedEstimator>();
mockedEstimator.Setup(e => e.GetCurrentStateIterator(It.IsAny<ChangeFeedEstimatorRequestOptions>())).Returns(mockedIterator.Object);
FeedEstimatorRunner estimatorCore = new FeedEstimatorRunner(estimatorDispatcher, mockedEstimator.Object, Mock.Of<ChangeFeedProcessorHealthMonitor>(), TimeSpan.FromMilliseconds(10));
try
{
await estimatorCore.RunAsync(cancellationTokenSource.Token);
}
catch (TaskCanceledException)
{
// expected
}
replacedert.IsTrue(detectedEstimationCorrectly);
}
19
Source : ChangeFeedIteratorCoreTests.cs
with MIT License
from Azure
with MIT License
from Azure
[TestMethod]
public async Task ChangeFeedIteratorCore_OnUnhandledException_HasMoreResults()
{
Exception exception = new Exception("oh no");
IDoreplacedentContainer doreplacedentContainer = await CreateDoreplacedentContainerAsync(
numItems: 0,
failureConfigs: new FlakyDoreplacedentContainer.FailureConfigs(
inject429s: false,
injectEmptyPages: false,
throwException: exception));
ChangeFeedIteratorCore changeFeedIteratorCore = new ChangeFeedIteratorCore(
doreplacedentContainer,
ChangeFeedMode.Incremental,
new ChangeFeedRequestOptions(),
ChangeFeedStartFrom.Beginning(),
this.MockClientContext());
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.Cancel();
try
{
ResponseMessage responseMessage = await changeFeedIteratorCore.ReadNextAsync();
replacedert.Fail("Should have thrown");
}
catch (Exception ex)
{
replacedert.AreEqual(exception, ex);
replacedert.IsTrue(changeFeedIteratorCore.HasMoreResults);
}
// If read a second time, it should not throw any missing page errors related to enumerators
try
{
ResponseMessage responseMessage = await changeFeedIteratorCore.ReadNextAsync();
replacedert.Fail("Should have thrown");
}
catch (Exception ex)
{
// TryCatch wraps any exception
replacedert.AreEqual(exception, ex);
replacedert.IsTrue(changeFeedIteratorCore.HasMoreResults);
}
}
See More Examples