本文整理汇总了C#中System.Threading.CancellationTokenSource类的典型用法代码示例。如果您正苦于以下问题:C# System.Threading.CancellationTokenSource类的具体用法?C# System.Threading.CancellationTokenSource怎么用?C# System.Threading.CancellationTokenSource使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
System.Threading.CancellationTokenSource类属于命名空间,在下文中一共展示了System.Threading.CancellationTokenSource类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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);
}
}
开发者ID:justinsaraceno,项目名称:openstack.net,代码行数:25,代码来源:UserLoadBalancerTests.cs
示例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);
}
开发者ID:HakanL,项目名称:animatroller,代码行数:35,代码来源:Renard.cs
示例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();
}
}
开发者ID:dfdcastro,项目名称:TDC2015,代码行数:34,代码来源:TileUpdaterTask.cs
示例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);
}
开发者ID:Altaxo,项目名称:Altaxo,代码行数:7,代码来源:PrintingControl.xaml.cs
示例5: OpenAsync
public async Task OpenAsync()
{
tcs = new System.Threading.CancellationTokenSource();
m_stream = await OpenStreamAsync();
StartParser();
MultiPartMessageCache.Clear();
}
开发者ID:krasilies,项目名称:NmeaParser,代码行数:7,代码来源:NmeaDevice.cs
示例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);
}
}
开发者ID:francisco-maciel,项目名称:FEUP-CMOV_StockQuotes,代码行数:60,代码来源:APIRequest.cs
示例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));
}
开发者ID:justinsaraceno,项目名称:openstack.net,代码行数:8,代码来源:UserQueuesTests.cs
示例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;
}
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:8,代码来源:CancellationCallbackInfo.cs
示例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();
}
}
开发者ID:charlyraffellini,项目名称:openstack.net,代码行数:8,代码来源:UserDatabaseUserTests.cs
示例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);
}
}
开发者ID:Healix,项目名称:Gw2Launcher,代码行数:58,代码来源:formMain.cs
示例11: SymbolProcessorTaskWorkDiconnectCancellationTest
public bool SymbolProcessorTaskWorkDiconnectCancellationTest()
{
if (null == _cts)
_cts = new System.Threading.CancellationTokenSource();
Disconnect();
base.OnNewDataReceived = SymbolProcessorTaskWorkCancellationTest;
dataQueue.CompleteAdding();
SymbolProcessorTaskWork();
return _dataReceived;
}
开发者ID:showtroylove,项目名称:MarketDataConsumer,代码行数:10,代码来源:MarketDataTests.cs
示例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();
}
开发者ID:jerryshen1987,项目名称:ZXing.Net.Mobile,代码行数:11,代码来源:ZXingSurfaceView.cs
示例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();
}
开发者ID:rainlabs-eu,项目名称:NmeaParser,代码行数:16,代码来源:NmeaDevice.cs
示例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));
}
开发者ID:kurzatem,项目名称:TheHUtil,代码行数:12,代码来源:PipelineManagerTests.cs
示例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;
}
}
开发者ID:mesenev,项目名称:hubbl,代码行数:14,代码来源:HubblUser.cs
示例16: CleanupTestQueues
public void CleanupTestQueues()
{
IQueueingService provider = CreateProvider();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TestTimeout(TimeSpan.FromSeconds(60)));
QueueName queueName = CreateRandomQueueName();
IEnumerable<Task<IEnumerable<CloudQueue>>> allQueueTasks = ListAllQueuesAsync(provider, null, false, cancellationTokenSource.Token);
CloudQueue[] allQueues = allQueueTasks.SelectMany(task => task.Result).ToArray();
Task[] deleteTasks = Array.ConvertAll(allQueues, queue =>
{
Console.WriteLine("Deleting queue: {0}", queue.Name);
return provider.DeleteQueueAsync(queue.Name, cancellationTokenSource.Token);
});
Task.WaitAll(deleteTasks);
}
开发者ID:justinsaraceno,项目名称:openstack.net,代码行数:15,代码来源:UserQueuesTests.cs
示例17: StartAsync
public async Task StartAsync()
{
if (tcs != null)
return;
if (m_device == null)
throw new ObjectDisposedException("Device");
tcs = new System.Threading.CancellationTokenSource();
socket = new StreamSocket();
await socket.ConnectAsync(
#if NETFX_CORE
m_device.ConnectionHostName,
m_device.ConnectionServiceName);
#else
m_device.HostName, "1");
//socket = await Windows.Networking.Proximity.PeerFinder.ConnectAsync(m_device.HostName;
#endif
if (tcs.IsCancellationRequested) //Stop was called while opening device
{
socket.Dispose();
socket = null;
throw new TaskCanceledException();
} var token = tcs.Token;
var _ = Task.Run(async () =>
{
var stream = socket.InputStream.AsStreamForRead();
byte[] buffer = new byte[1024];
while (!token.IsCancellationRequested)
{
int readCount = 0;
try
{
readCount = await stream.ReadAsync(buffer, 0, 1024, token).ConfigureAwait(false);
}
catch { }
if (token.IsCancellationRequested)
break;
if (readCount > 0)
{
OnData(buffer.Take(readCount).ToArray());
}
await Task.Delay(10, token);
}
if(socket != null)
socket.Dispose();
if (closeTask != null)
closeTask.SetResult(true);
});
}
开发者ID:syabiku,项目名称:BTDevices,代码行数:48,代码来源:Device.cs
示例18: TestCreateUser
public async Task TestCreateUser()
{
IDatabaseService provider = UserDatabaseTests.CreateProvider();
using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TestTimeout(TimeSpan.FromSeconds(600))))
{
string host = null;
UserName userName = UserDatabaseTests.CreateRandomUserName(host);
string password = UserDatabaseTests.CreateRandomPassword();
UserConfiguration userConfiguration = new UserConfiguration(userName, password);
await provider.CreateUserAsync(_instance.Id, userConfiguration, cancellationTokenSource.Token);
await provider.ListDatabaseUsersAsync(_instance.Id, null, null, cancellationTokenSource.Token);
await provider.RemoveUserAsync(_instance.Id, userName, cancellationTokenSource.Token);
}
}
开发者ID:charlyraffellini,项目名称:openstack.net,代码行数:16,代码来源:UserDatabaseUserTests.cs
示例19: Run
public override int Run()
{
Dictionary<string, object> argumentsToPass = new Dictionary<string, object>();
Console.WriteLine("{0} with arguments:", this.plan.Name);
foreach (ActionPropertyInfo s in this.expectedArguments)
{
Console.WriteLine("{0}: {1}", s.Name, this.GetArgument(s.Name));
argumentsToPass.Add(s.Name, this.GetArgument(s.Name));
}
foreach (ActionPropertyInfo s in this.optionalArguments)
{
var argValue = this.GetArgument(s.Name);
Console.WriteLine("{0}(optional): {1} - default value '{2}'", s.Name, argValue, s.Value);
if (argValue != null)
{
argumentsToPass.Add(s.Name, this.GetArgument(s.Name));
}
}
try
{
this.actionExecutionEngine.OnProgressChanged += this.ActionExecutionEngine_OnProgressChanged;
var cts = new System.Threading.CancellationTokenSource();
Task t = actionExecutionEngine.ExecuteAsync(this.plan, argumentsToPass, cts.Token);
t.Wait();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Exception inner = ex.InnerException;
while (inner != null)
{
Console.WriteLine(inner.Message);
inner = inner.InnerException;
}
this.retVal = -1;
}
return this.retVal;
}
开发者ID:HansKindberg-Net,项目名称:TFS-Branch-Tool,代码行数:45,代码来源:command.cs
示例20: MusicPlayer_PlaysMusic
public void MusicPlayer_PlaysMusic()
{
System.Diagnostics.Trace.WriteLine("Started");
MusicPlayer p = new MusicPlayer();
var ts = new System.Threading.CancellationTokenSource();
p.MuteUnMute();
Task.Factory.StartNew(p.PlayMusic, null, ts.Token);
System.Threading.Thread.Sleep(200);
string track1 = p.CurrentlyPlaying;
System.Diagnostics.Trace.WriteLine("Playing 1:" + track1.ToString());
p.PlayNext();
Assert.IsFalse(string.IsNullOrWhiteSpace(track1));
ts.Cancel(true);
System.Diagnostics.Trace.WriteLine("Stopped");
}
开发者ID:BujakiAttila,项目名称:LanguageBoosterGame,代码行数:18,代码来源:TestMusicPlayer.cs
注:本文中的System.Threading.CancellationTokenSource类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论