本文整理汇总了C#中TaskCompletionSource.SetException方法的典型用法代码示例。如果您正苦于以下问题:C# TaskCompletionSource.SetException方法的具体用法?C# TaskCompletionSource.SetException怎么用?C# TaskCompletionSource.SetException使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TaskCompletionSource
的用法示例。
在下文中一共展示了TaskCompletionSource.SetException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ReadJObject
public static Task<JObject> ReadJObject(this Socket socket)
{
var tcs = new TaskCompletionSource<JObject>();
socket.ReadBuffer(4)
.ContinueWith(task =>
{
try
{
var len = BitConverter.ToInt32(task.Result.Array, task.Result.Offset);
if(len > TenMB)
throw new InvalidOperationException("Got a reply for single JObject > 10 MB, rejecting as invalid");
socket.ReadBuffer(len)
.ContinueWith(readLenTask =>
{
try
{
var ms = new MemoryStream(readLenTask.Result.Array, readLenTask.Result.Offset,
readLenTask.Result.Count);
tcs.SetResult(ms.ToJObject());
}
catch (Exception e)
{
tcs.SetException(e);
}
});
}
catch (Exception e)
{
tcs.SetException(e);
}
});
return tcs.Task;
}
示例2: GetFeedAsync
public Task<SurveyNewsFeed> GetFeedAsync(string feedUrl) {
// We can't use a simple WebRequest, because that doesn't have access
// to the browser's session cookies. Cookies are used to remember
// which survey/news item the user has submitted/accepted. The server
// checks the cookies and returns the survey/news urls that are
// currently available (availability is determined via the survey/news
// item start and end date).
var tcs = new TaskCompletionSource<SurveyNewsFeed>();
try {
var thread = new Thread(() => {
var browser = new WebBrowser();
browser.DocumentCompleted += (sender, e) => {
try {
if (browser.Url == e.Url) {
SurveyNewsFeed feed = ParseFeed(browser);
tcs.SetResult(feed);
Application.ExitThread();
}
} catch (Exception ex2) {
tcs.SetException(ex2);
}
};
browser.Navigate(new Uri(feedUrl));
Application.Run();
});
thread.Name = "SurveyNewsFeedClient";
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
} catch (Exception ex1) {
tcs.SetException(ex1);
}
return tcs.Task;
}
示例3: RunAsync
public Task<RunSummary> RunAsync(IMessageSink diagnosticMessageSink, IMessageBus messageBus, object[] constructorArguments, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource)
{
var tcs = new TaskCompletionSource<RunSummary>();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
// Run on the UI thread
Device.BeginInvokeOnMainThread(
() =>
{
try
{
var result = testCase.RunAsync(diagnosticMessageSink, messageBus, constructorArguments, aggregator, cancellationTokenSource);
result.ContinueWith(t =>
{
if (t.IsFaulted)
tcs.SetException(t.Exception);
tcs.SetResult(t.Result);
});
}
catch (Exception e)
{
tcs.SetException(e);
}
});
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
return tcs.Task;
}
示例4: AddHandler
public Task AddHandler(string key, Func<string, IObservable<RedisObject>> handler, PublishOptions options)
{
var tcs = new TaskCompletionSource<object>();
try
{
_req.Create(key).Subscribe(req =>
{
try
{
if (req == null && !tcs.Task.IsCompleted)
{
tcs.SetResult(null);
return;
}
var ob = handler(req);
if (ob != null)
ob.ToRedis(req, _db);
}
catch (Exception e)
{
tcs.SetException(e);
}
});
}
catch (Exception e)
{
tcs.SetException(e);
}
return tcs.Task;
}
示例5: CloseAsync
public Task CloseAsync()
{
var tcsShutdown = new TaskCompletionSource<object>();
this.Task.ContinueWith(tpc =>
{
if (!tpc.IsFaulted)
{
this.PeerConnection.CloseAsync().ContinueWith(t =>
{
if (!t.IsFaulted)
{
tcsShutdown.SetResult(null); // complete
}
else
{
tcsShutdown.SetException(new TaskFailedException("Could not close (1).", t));
}
});
}
else
{
tcsShutdown.SetException(new TaskFailedException("Could not close (2).", tpc));
}
});
return tcsShutdown.Task;
}
示例6: Dispatch
public Task<Response> Dispatch(NancyContext context, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<Response>();
if (cancellationToken.IsCancellationRequested)
{
tcs.SetException(new OperationCanceledException());
return tcs.Task;
}
if (context == null)
{
tcs.SetException(new ArgumentException("context is null"));
return tcs.Task;
}
var response = IsAdminRequest(context.Request) ?
_adminRequestHandler.Handle(context) :
_requestHandler.Handle(context);
context.Response = response;
tcs.SetResult(context.Response);
return tcs.Task;
}
示例7: GetResponseAsync
public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request)
{
var tcs = new TaskCompletionSource<HttpWebResponse>();
try
{
request.BeginGetResponse(iar =>
{
try
{
var response = (HttpWebResponse)request.EndGetResponse(iar);
tcs.SetResult(response);
}
catch (Exception exc)
{
tcs.SetException(exc);
}
}, null);
}
catch (Exception exc)
{
tcs.SetException(exc);
}
return tcs.Task;
}
示例8: CloseAsync
/// <summary>
/// Closes an AMQP object asynchronously.
/// </summary>
/// <param name="amqpObject">The object to close.</param>
/// <param name="timeout">The timeout in seconds.</param>
/// <returns></returns>
public static Task CloseAsync(this AmqpObject amqpObject, int timeout = 60000)
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
try
{
amqpObject.Closed += (o, e) =>
{
if (e != null)
{
tcs.SetException(new AmqpException(e));
}
else
{
tcs.SetResult(null);
}
};
amqpObject.Close(0);
}
catch (Exception exception)
{
tcs.SetException(exception);
}
return tcs.Task;
}
示例9: LoadAtLeastOne
public static Task<ReadableArticleViewModel> LoadAtLeastOne(ISimpleHttpService httpService, string url, string linkId)
{
TaskCompletionSource<ReadableArticleViewModel> result = new TaskCompletionSource<ReadableArticleViewModel>();
var articleViewModel = new ReadableArticleViewModel { ArticleUrl = url, ArticleParts = new ObservableCollection<object>(), LinkId = linkId, ContentIsFocused = true };
LoadOneImpl(httpService, url, articleViewModel.ArticleParts).ContinueWith(async (task) =>
{
try
{
if (task.IsCompleted)
{
Tuple<string, string> tpl = await task;
var nextPage = tpl.Item1;
articleViewModel.Title = tpl.Item2;
result.SetResult(articleViewModel);
if (!string.IsNullOrEmpty(nextPage))
{
var remainingParts = await Task.Run(() => LoadFullyImpl(httpService, nextPage));
foreach (var part in remainingParts.Item2)
{
articleViewModel.ArticleParts.Add(part);
}
}
}
else if (task.Exception != null)
result.SetException(task.Exception);
}
catch (Exception ex)
{
result.SetException(ex);
}
}, TaskScheduler.FromCurrentSynchronizationContext());
return result.Task;
}
示例10: CreateRedisConnection
public Task<RedisConnection> CreateRedisConnection()
{
var settings = RedisConnectionProvider.Instance.ConnectionsSettings;
var redisConnection = new RedisConnection(host: settings["host"], port: Convert.ToInt32(settings["port"]), password: settings["password"]);
var taskCreateConnection = new TaskCompletionSource<RedisConnection>();
try
{
redisConnection.Open().ContinueWith((task) =>
{
if (!task.IsFaulted)
{
taskCreateConnection.SetResult(redisConnection);
}
else
{
task.Exception.Handle(x => true);
taskCreateConnection.SetException(task.Exception);
}
}, TaskScheduler.Default);
}
catch (Exception ex)
{
taskCreateConnection.SetException(ex);
}
return taskCreateConnection.Task;
}
示例11: GetAsset
Task<ALAsset> GetAsset (AssetDescription description, CancellationToken token)
{
var tcs = new TaskCompletionSource<ALAsset> ();
Task.Factory.StartNew (() => {
if (token.IsCancellationRequested) {
tcs.SetCanceled ();
return;
}
_library.Value.AssetForUrl (new NSUrl (description.AssetUrl), (asset) => {
if (asset == null) {
tcs.SetException (new Exception ("No asset found for url"));
return;
}
if (asset.DefaultRepresentation == null) {
tcs.SetException (new Exception ("No representation found for the asset"));
return;
}
tcs.SetResult (asset);
}, error => {
tcs.SetException (new Exception (error.ToString ()));
});
}, token).RouteExceptions (tcs);
return tcs.Task;
}
示例12: GetRequestStreamAsync
/// <summary>
/// Async method for getting web request.
/// </summary>
/// <param name="request">The HttpWebRequest instance.</param>
/// <returns>The request stream asynchronuously.</returns>
public static Task<Stream> GetRequestStreamAsync(this HttpWebRequest request)
{
Contract.Requires<ArgumentNullException>(request != null);
var tcs = new TaskCompletionSource<Stream>();
try
{
request.BeginGetRequestStream(iar =>
{
try
{
var response = request.EndGetRequestStream(iar);
tcs.SetResult(response);
}
catch (Exception exc)
{
tcs.SetException(exc);
}
}, null);
}
catch (Exception exc)
{
tcs.SetException(exc);
}
return tcs.Task;
}
示例13: GetResponseAsync
public Task<WebResponse> GetResponseAsync(HttpWebRequest request, int timeoutMs)
{
if (timeoutMs > 0)
{
return GetResponseAsync(request, TimeSpan.FromMilliseconds(timeoutMs));
}
var tcs = new TaskCompletionSource<WebResponse>();
try
{
request.BeginGetResponse(iar =>
{
try
{
var response = (HttpWebResponse)request.EndGetResponse(iar);
tcs.SetResult(response);
}
catch (Exception exc)
{
tcs.SetException(exc);
}
}, null);
}
catch (Exception exc)
{
tcs.SetException(exc);
}
return tcs.Task;
}
示例14: GetContentAsync
public Task<string> GetContentAsync(string url)
{
var tcs = new TaskCompletionSource<string>();
try
{
var client = new RestClient(url);
client.GetAsync(new RestRequest(), (response, handle) =>
{
if ((int)response.StatusCode >= 400)
{
tcs.SetException(new Exception(response.StatusDescription));
}
else
{
tcs.SetResult(response.Content);
}
});
}
catch (Exception ex)
{
tcs.SetException(ex);
}
return tcs.Task;
}
示例15: StartProcess
public static Task<int> StartProcess (ProcessStartInfo psi, TextWriter stdout, TextWriter stderr, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<int> ();
if (cancellationToken.CanBeCanceled && cancellationToken.IsCancellationRequested) {
tcs.SetCanceled ();
return tcs.Task;
}
psi.UseShellExecute = false;
if (stdout != null) {
psi.RedirectStandardOutput = true;
}
if (stderr != null) {
psi.RedirectStandardError = true;
}
var p = Process.Start (psi);
if (cancellationToken.CanBeCanceled)
cancellationToken.Register (() => {
try {
if (!p.HasExited) {
p.Kill ();
}
} catch (InvalidOperationException ex) {
if (ex.Message.IndexOf ("already exited") < 0)
throw;
}
});
p.EnableRaisingEvents = true;
if (psi.RedirectStandardOutput) {
bool stdOutInitialized = false;
p.OutputDataReceived += (sender, e) => {
try {
if (stdOutInitialized)
stdout.WriteLine ();
stdout.Write (e.Data);
stdOutInitialized = true;
} catch (Exception ex) {
tcs.SetException (ex);
}
};
p.BeginOutputReadLine ();
}
if (psi.RedirectStandardError) {
bool stdErrInitialized = false;
p.ErrorDataReceived += (sender, e) => {
try {
if (stdErrInitialized)
stderr.WriteLine ();
stderr.Write (e.Data);
stdErrInitialized = true;
} catch (Exception ex) {
tcs.SetException (ex);
}
};
p.BeginErrorReadLine ();
}
p.Exited += (sender, e) => tcs.SetResult (p.ExitCode);
return tcs.Task;
}