在异步任务中捕获异常

编程入门 行业动态 更新时间:2024-10-06 18:32:01
本文介绍了在异步任务中捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用C#(控制台应用程序).

I'm working in C# (console application).

在我的程序中,我必须联系httpClient.首先,我检查客户端是否使用GetAsync进行响应.所以我的请求方法是异步的,使我的任务异步了.

In my program, I have to contact a httpClient. First I check if the client is responding using GetAsync. So my request method is async, making my Task async.

当客户端不响应(或其他响应)时,它会引发异常,但我无法捕获它.

When client doesn't respond (or something else) it throw an exception but i'm unable to catch it.

我添加了ContinueWith,但是它不起作用.有了breackpoint,我看到在我的Task的开头已经到达了这段代码,因此异常始终为null.

I added a ContinueWith but it doesn't work. With a breackpoint I saw that the piece of code is reached at the start of my Task so the exception is always null.

我该如何解决这个问题?

How can I solve this problem ?

有我的代码:

static void Run() { String urlRequest = ""; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; Console.WriteLine($"Program running, press a key to stop"); try { Task task = Task.Factory.StartNew(async () => { using (HttpClientHandler handler = new HttpClientHandler { Credentials = new NetworkCredential("user", "pass") }) { HttpClient client = new HttpClient(handler); client.BaseAddress = new Uri(urlRequest); client.DefaultRequestHeaders.Accept.Clear(); bool serviceAvailable = await CheckService(client); if (serviceAvailable) { bool doLoop = true; while (doLoop) { // Do something Thread.Sleep(100); if (ct.IsCancellationRequested) { Console.WriteLine("\r\ntask cancelled"); break; } } } else { throw new HttpRequestException($"Unable to contact service at {urlRequest}"); } } }, ct).ContinueWith(tsk => { if (tsk.Exception != null) throw tsk.Exception; }); Console.ReadKey(); cts.Cancel(); Thread.Sleep(1000); } catch (Exception e) { Log(e); } } static async Task<bool> CheckClient(HttpClient client) { Console.WriteLine("Check service Call ..."); HttpResponseMessage response = await client.GetAsync("CheckService"); if (response.IsSuccessStatusCode) { return true; } return false; }

推荐答案

您既不等待也不观察任务的结果.假设您是针对.Net 4.5或更高版本运行此程序,则存在该异常,但它并未引起注意.

You are neither waiting for nor observing the result of your task. Assuming that you're running this against .Net 4.5 or later, the exception is there but it is going unnoticed.

因此,首先,您应该.Wait()完成任务,以便调用代码有机会观察到异常.

So, first of all, you should .Wait() for your task to complete so that the calling code has a chance to observe the exception.

通常来说,您应该避免使用Task.Factory.StartNew(),而更喜欢使用Task.Run()-请参阅斯蒂芬·图布(Stephen Toub)解释原因.但是,如果出于某种原因更喜欢使用Task.Factory.StartNew,则还必须首先.Unwrap()原始任务才能获得想要获得结果的实际任务. (请注意,.Unrwap()是扩展方法,可用于Task<Task>,但不能用于Task,因此请相应地键入原始变量;即,使用var task = Task.Factory.StartNew(...))

Generally speaking, you should avoid using Task.Factory.StartNew() and prefer Task.Run() instead - see Stephen Toub's explanation why. But if you prefer to use Task.Factory.StartNew for whatever reason, then you additionally must first .Unwrap() the original task to obtain the actual task for which you want the result. (Do note that .Unrwap() is an extension method that is available for Task<Task> but not Task, so type the original variable accordingly; i.e., use var task = Task.Factory.StartNew(...))

更多推荐

在异步任务中捕获异常

本文发布于:2023-11-05 10:27:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560584.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!