本文整理汇总了C#中TaskCompletionSource.TrySetCanceled方法的典型用法代码示例。如果您正苦于以下问题:C# TaskCompletionSource.TrySetCanceled方法的具体用法?C# TaskCompletionSource.TrySetCanceled怎么用?C# TaskCompletionSource.TrySetCanceled使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TaskCompletionSource
的用法示例。
在下文中一共展示了TaskCompletionSource.TrySetCanceled方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Then
public static Task Then(Task first, Func<Task> next)
{
var tcs = new TaskCompletionSource<object>();
first.ContinueWith(_ =>
{
if (first.IsFaulted){
tcs.TrySetException(first.Exception.InnerExceptions);
}
else if (first.IsCanceled){
tcs.TrySetCanceled();
}
else
{
try
{
next().ContinueWith(t => {
if (t.IsFaulted) {
tcs.TrySetException(t.Exception.InnerExceptions);
}
else if (t.IsCanceled) {
tcs.TrySetCanceled();
}
else {
tcs.TrySetResult(null);
}
}, TaskContinuationOptions.ExecuteSynchronously);
}
catch (Exception exc) { tcs.TrySetException(exc); }
}
}, TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
示例2: WriteAsync
public static Task WriteAsync(this Stream stream, byte[] buffer, int offset, int count,
CancellationToken cancel = default(CancellationToken))
{
cancel.ThrowIfCancellationRequested();
var tcs = new TaskCompletionSource<object>();
var sr = stream.BeginWrite(buffer, offset, count, ar =>
{
if (ar.CompletedSynchronously)
{
return;
}
try
{
stream.EndWrite(ar);
tcs.SetResult(null);
}
catch (Exception ex)
{
// Assume errors were caused by cancelation.
if (cancel.IsCancellationRequested)
{
tcs.TrySetCanceled();
}
tcs.SetException(ex);
}
}, null);
if (sr.CompletedSynchronously)
{
try
{
stream.EndWrite(sr);
tcs.SetResult(null);
}
catch (Exception ex)
{
// Assume errors were caused by cancelation.
if (cancel.IsCancellationRequested)
{
tcs.TrySetCanceled();
}
tcs.SetException(ex);
}
}
return tcs.Task;
}
示例3: RunAsync
public async Task RunAsync(Graph graph, Stream outputStream, RendererLayouts layout, RendererFormats format, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var fileName = Path.Combine(graphvizBin, GetRendererLayoutExecutable(layout));
var arguments = GetRendererFormatArgument(format);
var startInfo = new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
var tcs = new TaskCompletionSource<object>();
using (var process = Process.Start(startInfo))
{
cancellationToken.ThrowIfCancellationRequested();
cancellationToken.Register(() =>
{
tcs.TrySetCanceled();
process.CloseMainWindow();
});
using (var standardInput = process.StandardInput)
{
graph.WriteTo(standardInput);
}
using (var standardOutput = process.StandardOutput)
{
await Task.WhenAny(tcs.Task, standardOutput.BaseStream.CopyToAsync(outputStream, 4096, cancellationToken));
}
}
cancellationToken.ThrowIfCancellationRequested();
}
示例4: AsAsyncResult
/// <summary>
/// A helper method for mocking APM (classic) asynchronous methods with on TAP (modern) asynchronous methods.
/// </summary>
/// <remarks>
/// This is based on <a href="http://blogs.msdn.com/b/pfxteam/archive/2011/06/27/10179452.aspx"/>
/// and <a href="http://msdn.microsoft.com/en-us/library/hh873178.aspx"/>.
/// </remarks>
public static IAsyncResult AsAsyncResult(this Task task, AsyncCallback callback, object state)
{
Debug.Assert(task != null, "task");
var taskCompletionSource = new TaskCompletionSource<object>(state);
task.ContinueWith(
t =>
{
if (t.IsFaulted)
{
taskCompletionSource.TrySetException(t.Exception.InnerExceptions);
}
else if (t.IsCanceled)
{
taskCompletionSource.TrySetCanceled();
}
else
{
taskCompletionSource.SetResult(null);
}
if (callback != null)
{
callback(taskCompletionSource.Task);
}
},
TaskScheduler.Default);
return taskCompletionSource.Task;
}
示例5: RunAsync
public static Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationToken cancellationToken)
{
if (processStartInfo == null)
{
throw new ArgumentNullException("processStartInfo");
}
// force some settings in the start info so we can capture the output
processStartInfo.UseShellExecute = false;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.CreateNoWindow = true;
var tcs = new TaskCompletionSource<ProcessResults>();
var standardOutput = new List<string>();
var standardError = new List<string>();
var process = new Process
{
StartInfo = processStartInfo,
EnableRaisingEvents = true,
};
process.OutputDataReceived += (sender, args) =>
{
if (args.Data != null)
{
standardOutput.Add(args.Data);
}
};
process.ErrorDataReceived += (sender, args) =>
{
if (args.Data != null)
{
standardError.Add(args.Data);
}
};
process.Exited += (sender, args) => tcs.TrySetResult(new ProcessResults(process, standardOutput, standardError));
cancellationToken.Register(() =>
{
tcs.TrySetCanceled();
process.CloseMainWindow();
});
cancellationToken.ThrowIfCancellationRequested();
if (process.Start() == false)
{
tcs.TrySetException(new InvalidOperationException("Failed to start process"));
}
process.BeginOutputReadLine();
process.BeginErrorReadLine();
return tcs.Task;
}
示例6: RSessionEvaluation
public RSessionEvaluation(IReadOnlyList<IRContext> contexts, IRExpressionEvaluator evaluator, CancellationToken ct) {
Contexts = contexts;
_evaluator = evaluator;
_tcs = new TaskCompletionSource<object>();
_ct = ct;
ct.Register(() => _tcs.TrySetCanceled());
}
示例7: SmoothSetAsync
public static Task SmoothSetAsync(this FrameworkElement @this, DependencyProperty dp, double targetvalue,
TimeSpan iDuration, CancellationToken iCancellationToken)
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
DoubleAnimation anim = new DoubleAnimation(targetvalue, new Duration(iDuration));
PropertyPath p = new PropertyPath("(0)", dp);
Storyboard.SetTargetProperty(anim, p);
Storyboard sb = new Storyboard();
sb.Children.Add(anim);
EventHandler handler = null;
handler = delegate
{
sb.Completed -= handler;
sb.Remove(@this);
@this.SetValue(dp, targetvalue);
tcs.TrySetResult(null);
};
sb.Completed += handler;
sb.Begin(@this, true);
iCancellationToken.Register(() =>
{
double v = (double)@this.GetValue(dp);
sb.Stop();
sb.Remove(@this);
@this.SetValue(dp, v);
tcs.TrySetCanceled();
});
return tcs.Task;
}
示例8: StartNewDelayed
public static Task StartNewDelayed(this TaskFactory factory, int millisecondsDelay, CancellationToken cancellationToken = default(CancellationToken)) {
// Validate arguments
if (factory == null)
throw new ArgumentNullException(nameof(factory));
if (millisecondsDelay < 0)
throw new ArgumentOutOfRangeException(nameof(millisecondsDelay));
// Create the timed task
var tcs = new TaskCompletionSource<object>(factory.CreationOptions);
var ctr = default(CancellationTokenRegistration);
// Create the timer but don't start it yet. If we start it now,
// it might fire before ctr has been set to the right registration.
var timer = new Timer(self => {
// Clean up both the cancellation token and the timer, and try to transition to completed
ctr.Dispose();
(self as Timer)?.Dispose();
tcs.TrySetResult(null);
}, null, -1, -1);
// Register with the cancellation token.
if (cancellationToken.CanBeCanceled) {
// When cancellation occurs, cancel the timer and try to transition to canceled.
// There could be a race, but it's benign.
ctr = cancellationToken.Register(() => {
timer.Dispose();
tcs.TrySetCanceled();
});
}
// Start the timer and hand back the task...
timer.Change(millisecondsDelay, Timeout.Infinite);
return tcs.Task;
}
示例9: ToApm
/// <summary>
/// A Task extension method that converts this object to an IAsyncResult.
/// </summary>
/// <remarks>
/// Mark, 19/06/2012.
/// Props to Stephen Toub for this blog post:
/// http://blogs.msdn.com/b/pfxteam/archive/2011/06/27/10179452.aspx
/// </remarks>
/// <param name="task"> The task to act on.</param>
/// <param name="callback">The callback.</param>
/// <param name="state">The state.</param>
/// <returns>
/// The given data converted to an IAsyncResult-y Task.
/// </returns>
public static Task ToApm(this Task task, AsyncCallback callback, object state)
{
task = task ?? MakeCompletedTask();
var tcs = new TaskCompletionSource<object>();
task.ContinueWith(t =>
{
if (t.IsFaulted)
{
tcs.TrySetException(t.Exception.InnerExceptions);
}
else if (t.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
tcs.TrySetResult(null);
}
if (callback != null)
{
callback(tcs.Task);
}
}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
return tcs.Task;
}
示例10: ClientCancellationBeforeResponseHeadersReceived_ResetSent
public Task ClientCancellationBeforeResponseHeadersReceived_ResetSent()
{
ManualResetEvent waitForRequest = new ManualResetEvent(false);
ManualResetEvent waitForClientCancel = new ManualResetEvent(false);
ManualResetEvent waitForServerCancel = new ManualResetEvent(false);
bool serverCancelled = false;
return RunSessionAsync(
(AppFunc)(env =>
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
CancellationToken token = (CancellationToken)env["owin.CallCancelled"];
token.Register(() =>
{
serverCancelled = true;
waitForServerCancel.Set();
tcs.TrySetCanceled();
});
waitForRequest.Set();
return tcs.Task;
}),
async (clientSession, serverSession) =>
{
CancellationTokenSource clientCancel = new CancellationTokenSource();
IList<KeyValuePair<string, string>> requestPairs = GenerateHeaders("GET");
Http2ClientStream clientProtocolStream = clientSession.SendRequest(requestPairs, null, 3, false, clientCancel.Token);
Task<IList<KeyValuePair<string, string>>> responseTask = clientProtocolStream.GetResponseAsync();
waitForRequest.WaitOne();
clientCancel.Cancel();
Assert.True(responseTask.IsCanceled);
waitForClientCancel.Set();
waitForServerCancel.WaitOne();
Assert.True(serverCancelled);
});
}
示例11: LoginAsync
/// <summary>
/// Login a user into an Auth0 application by showing an embedded browser window either showing the widget or skipping it by passing a connection name
/// </summary>
/// <param name="owner">The owner window</param>
/// <param name="connection">Optional connection name to bypass the login widget</param>
/// <param name="scope">Optional. Scope indicating what attributes are needed. "openid" to just get the user_id or "openid profile" to get back everything.
/// <remarks>When using openid profile if the user has many attributes the token might get big and the embedded browser (Internet Explorer) won't be able to parse a large URL</remarks>
/// </param>
/// <returns>Returns a Task of Auth0User</returns>
public Task<Auth0User> LoginAsync(IWin32Window owner, string connection = "", string scope = "openid")
{
var tcs = new TaskCompletionSource<Auth0User>();
var auth = this.GetAuthenticator(connection, scope);
auth.Error += (o, e) =>
{
var ex = e.Exception ?? new UnauthorizedAccessException(e.Message);
tcs.TrySetException(ex);
};
auth.Completed += (o, e) =>
{
if (!e.IsAuthenticated)
{
tcs.TrySetCanceled();
}
else
{
if (this.State != e.Account.State)
{
tcs.TrySetException(new UnauthorizedAccessException("State does not match"));
}
else
{
this.SetupCurrentUser(e.Account);
tcs.TrySetResult(this.CurrentUser);
}
}
};
auth.ShowUI(owner);
return tcs.Task;
}
示例12: ReadFromStreamAsync
public override Task<object> ReadFromStreamAsync(Type type, HttpContentHeaders headers, Stream stream)
{
var tcs = new TaskCompletionSource<object>();
try {
var serializer = GetSerializerForType(type);
if (serializer == null) {
tcs.TrySetException(new InvalidOperationException(string.Format("Can not create serializer for {0}", type)));
}
else {
Task<object>.Factory.StartNew(() => serializer.Deserialize(stream))
.ContinueWith(t => {
if (t.IsFaulted) {
tcs.TrySetException(t.Exception.GetBaseException());
}
else if (t.IsCanceled) {
tcs.TrySetCanceled();
}
else {
tcs.TrySetResult(t.Result);
}
}, TaskContinuationOptions.ExecuteSynchronously);
}
}
catch (Exception ex) {
tcs.TrySetException(ex);
}
return tcs.Task;
}
示例13: BeginJavascriptCallbackAsync
public IAsyncResult BeginJavascriptCallbackAsync(int browserId, long callbackId, object[] parameters, TimeSpan? timeout, AsyncCallback callback, object state)
{
var tcs = new TaskCompletionSource<JavascriptResponse>(state);
var task = JavascriptCallbackAsync(browserId, callbackId, parameters, timeout);
task.ContinueWith(t =>
{
if (t.IsFaulted)
{
tcs.TrySetException(t.Exception.InnerExceptions);
}
else if (t.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
tcs.TrySetResult(t.Result);
}
if (callback != null)
{
callback(tcs.Task);
}
});
return tcs.Task;
}
示例14: WaitAsync
public Task WaitAsync(CancellationToken cancellationToken = default(CancellationToken))
{
lock (this.waitersQueue)
{
// Make sure we're not already cancelled.
if (cancellationToken.IsCancellationRequested)
throw new TaskCanceledException();
// If we already have tokens, we can return immediatly.
if (this.currentCount > 0)
{
this.currentCount--;
return CompletedTask;
}
// Otherwise, create the waiter and queue it.
var waiter = new TaskCompletionSource<bool>();
// Register on the cancellation token for the waiter cancellation.
cancellationToken.Register(() => waiter.TrySetCanceled());
// Make sure we haven't been canceled in the meantime.
if (cancellationToken.IsCancellationRequested)
throw new TaskCanceledException();
this.waitersQueue.Enqueue(waiter);
return waiter.Task;
}
}
示例15: DownloadFileAsyncCore
public static Task<bool> DownloadFileAsyncCore(WebClient webClient, Uri address, string fileName)
{
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(webClient);
AsyncCompletedEventHandler handler = null;
handler = (sender, e) =>
{
if (e.UserState != webClient) return;
if (e.Cancelled) tcs.TrySetCanceled();
else if (e.Error != null) tcs.TrySetException(e.Error);
else tcs.TrySetResult(true);
webClient.DownloadFileCompleted -= handler;
};
webClient.DownloadFileCompleted += handler;
try
{
webClient.DownloadFileAsync(address, fileName, webClient);
}
catch (Exception ex)
{
webClient.DownloadFileCompleted -= handler;
tcs.TrySetException(ex);
}
return tcs.Task;
}