本文整理汇总了C#中System.Threading.CancellationTokenSource类的典型用法代码示例。如果您正苦于以下问题:C# System.Threading.CancellationTokenSource类的具体用法?C# System.Threading.CancellationTokenSource怎么用?C# System.Threading.CancellationTokenSource使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
System.Threading.CancellationTokenSource类属于命名空间,在下文中一共展示了System.Threading.CancellationTokenSource类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CleanupTestLoadBalancers
public async Task CleanupTestLoadBalancers()
{
ILoadBalancerService provider = CreateProvider();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TestTimeout(TimeSpan.FromSeconds(60)));
string queueName = CreateRandomLoadBalancerName();
LoadBalancer[] allLoadBalancers = ListAllLoadBalancers(provider, null, cancellationTokenSource.Token).Where(loadBalancer => loadBalancer.Name.StartsWith(TestLoadBalancerPrefix, StringComparison.OrdinalIgnoreCase)).ToArray();
int blockSize = 10;
for (int i = 0; i < allLoadBalancers.Length; i += blockSize)
{
await provider.RemoveLoadBalancerRangeAsync(
allLoadBalancers
.Skip(i)
.Take(blockSize)
.Select(loadBalancer =>
{
Console.WriteLine("Deleting load balancer: {0}", loadBalancer.Name);
return loadBalancer.Id;
})
.ToArray(), // included to ensure the Console.WriteLine is only executed once per load balancer
AsyncCompletionOption.RequestCompleted,
cancellationTokenSource.Token,
null);
}
}
示例2: Renard
public Renard(string portName)
{
this.serialPort = new SerialPort(portName, 57600);
this.renardData = new byte[24];
this.cancelSource = new System.Threading.CancellationTokenSource();
this.firstChange = new System.Diagnostics.Stopwatch();
this.senderTask = new Task(x =>
{
while (!this.cancelSource.IsCancellationRequested)
{
bool sentChanges = false;
lock (lockObject)
{
if (this.dataChanges > 0)
{
this.firstChange.Stop();
//log.Info("Sending {0} changes to Renard. Oldest {1:N2}ms",
// this.dataChanges, this.firstChange.Elapsed.TotalMilliseconds);
this.dataChanges = 0;
sentChanges = true;
SendSerialData(this.renardData);
}
}
if(!sentChanges)
System.Threading.Thread.Sleep(10);
}
}, this.cancelSource.Token, TaskCreationOptions.LongRunning);
Executor.Current.Register(this);
}
示例3: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
// Check the task cost
var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
if (cost == BackgroundWorkCostValue.High)
{
return;
}
// Get the cancel token
var cancel = new System.Threading.CancellationTokenSource();
taskInstance.Canceled += (s, e) =>
{
cancel.Cancel();
cancel.Dispose();
};
// Get deferral
var deferral = taskInstance.GetDeferral();
try
{
// Update Tile with the new xml
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(TileUpdaterTask.w10TileXml);
TileNotification tileNotification = new TileNotification(xmldoc);
TileUpdater tileUpdator = TileUpdateManager.CreateTileUpdaterForApplication();
tileUpdator.Update(tileNotification);
}
finally
{
deferral.Complete();
}
}
示例4: EhLoaded
private void EhLoaded(object sender, RoutedEventArgs e)
{
this._printerStatusCancellationTokenSource = new System.Threading.CancellationTokenSource();
this._printerStatusCancellationToken = _printerStatusCancellationTokenSource.Token;
System.Threading.Tasks.Task.Factory.StartNew(UpdatePrinterStatusGuiElements, _printerStatusCancellationToken);
}
示例5: OpenAsync
public async Task OpenAsync()
{
tcs = new System.Threading.CancellationTokenSource();
m_stream = await OpenStreamAsync();
StartParser();
MultiPartMessageCache.Clear();
}
示例6: Execute
public async void Execute(string token, string content)
{
Uri uri = new Uri(API_ADDRESS + path);
var rootFilter = new HttpBaseProtocolFilter();
rootFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
rootFilter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;
HttpClient client = new HttpClient(rootFilter);
//client.DefaultRequestHeaders.Add("timestamp", DateTime.Now.ToString());
if(token != null)
client.DefaultRequestHeaders.Add("x-access-token", token);
System.Threading.CancellationTokenSource source = new System.Threading.CancellationTokenSource(2000);
HttpResponseMessage response = null;
if (requestType == GET)
{
try
{
response = await client.GetAsync(uri).AsTask(source.Token);
}
catch (TaskCanceledException)
{
response = null;
}
}else if (requestType == POST)
{
HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), uri);
if (content != null)
{
msg.Content = new HttpStringContent(content);
msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");
}
try
{
response = await client.SendRequestAsync(msg).AsTask(source.Token);
}
catch (TaskCanceledException)
{
response = null;
}
}
if (response == null)
{
if (listener != null)
listener.onTaskCompleted(null, requestCode);
}
else
{
string answer = await response.Content.ReadAsStringAsync();
if(listener != null)
listener.onTaskCompleted(answer, requestCode);
}
}
示例7: TestGetHome
public async Task TestGetHome()
{
IQueueingService provider = CreateProvider();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TestTimeout(TimeSpan.FromSeconds(10)));
HomeDocument document = await provider.GetHomeAsync(cancellationTokenSource.Token);
Assert.IsNotNull(document);
Console.WriteLine(JsonConvert.SerializeObject(document, Formatting.Indented));
}
示例8: CancellationCallbackInfo
internal CancellationCallbackInfo(Action<object> callback, object stateForCallback, SynchronizationContext targetSyncContext, ExecutionContext targetExecutionContext, System.Threading.CancellationTokenSource cancellationTokenSource)
{
this.Callback = callback;
this.StateForCallback = stateForCallback;
this.TargetSyncContext = targetSyncContext;
this.TargetExecutionContext = targetExecutionContext;
this.CancellationTokenSource = cancellationTokenSource;
}
示例9: ClassCleanup
public static void ClassCleanup()
{
IDatabaseService provider = UserDatabaseTests.CreateProvider();
using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TestTimeout(TimeSpan.FromSeconds(600))))
{
provider.RemoveDatabaseInstanceAsync(_instance.Id, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null).Wait();
}
}
示例10: Launcher_BuildUpdated
void Launcher_BuildUpdated(Client.Launcher.BuildUpdatedEventArgs e)
{
HashSet<Settings.IDatFile> dats = new HashSet<Settings.IDatFile>();
List<Settings.IAccount> accounts = new List<Settings.IAccount>();
//only accounts with a unique dat file need to be updated
foreach (ushort uid in Settings.Accounts.GetKeys())
{
var a = Settings.Accounts[uid];
if (a.HasValue && (a.Value.DatFile == null || dats.Add(a.Value.DatFile)))
{
accounts.Add(a.Value);
}
}
if (accounts.Count > 0)
{
System.Threading.CancellationTokenSource cancel = new System.Threading.CancellationTokenSource(3000);
try
{
this.BeginInvoke(new MethodInvoker(
delegate
{
BeforeShowDialog();
try
{
activeWindows++;
using (formUpdating f = new formUpdating(accounts, true, true))
{
f.Shown += delegate
{
cancel.Cancel();
};
f.ShowDialog(this);
}
}
finally
{
activeWindows--;
}
}));
}
catch { }
try
{
cancel.Token.WaitHandle.WaitOne();
}
catch (Exception ex)
{
ex = ex;
}
e.Update(accounts);
}
}
示例11: SymbolProcessorTaskWorkDiconnectCancellationTest
public bool SymbolProcessorTaskWorkDiconnectCancellationTest()
{
if (null == _cts)
_cts = new System.Threading.CancellationTokenSource();
Disconnect();
base.OnNewDataReceived = SymbolProcessorTaskWorkCancellationTest;
dataQueue.CompleteAdding();
SymbolProcessorTaskWork();
return _dataReceived;
}
示例12: ZXingSurfaceView
protected ZXingSurfaceView(IntPtr javaReference, JniHandleOwnership transfer)
: base(javaReference, transfer)
{
lastPreviewAnalysis = DateTime.Now.AddMilliseconds(options.InitialDelayBeforeAnalyzingFrames);
this.surface_holder = Holder;
this.surface_holder.AddCallback(this);
this.surface_holder.SetType(SurfaceType.PushBuffers);
this.tokenSource = new System.Threading.CancellationTokenSource();
}
示例13: OpenAsync
/// <summary>
/// Opens the device connection.
/// </summary>
/// <returns></returns>
public async Task OpenAsync()
{
lock (m_lockObject)
{
if (IsOpen) return;
IsOpen = true;
}
m_cts = new System.Threading.CancellationTokenSource();
m_stream = await OpenStreamAsync();
StartParser();
MultiPartMessageCache.Clear();
}
示例14: shouldCancelDuringBuild
public async Task shouldCancelDuringBuild()
{
var cancellationTestee = new PipelineManager();
var canceller = new System.Threading.CancellationTokenSource();
var progressReporter = new PipelineProgress(canceller.Cancel, 50, false);
var result = await cancellationTestee.BuildPipelineAsync(this.scheme, canceller.Token, progressReporter, new TestSubject());
var refinedResults = result.Select(r => r.Outcome).ToArray();
Assert.IsTrue(refinedResults.Contains(StepBuildResults.Cancelled) && refinedResults.Contains(StepBuildResults.Completed), "Token may have expirec before the build took place.\nResults are:\n" + refinedResults.PrintContentsToString(Environment.NewLine));
}
示例15: LoadUser
public static HubblUser LoadUser()
{
var source = new System.Threading.CancellationTokenSource (10000);
var token = source.Token;
try {
var file = FileSystem.Current.LocalStorage.GetFileAsync ("user", token).Result;
var sUser = file.ReadAllTextAsync ().Result;
var user = JsonConvert.DeserializeObject<HubblUser>(sUser);
user.IsHub = false;
return user;
} catch (Exception) {
return null;
}
}