使用Microsoft for .NET的异步CTP,是否可以捕获调用方法中异步方法抛出的异常?
public async void Foo()
{
var x = await DoSomethingAsync();
/* Handle the result, but sometimes an exception might be thrown.
For example, DoSomethingAsync gets data from the network
and the data is invalid... a ProtocolException might be thrown. */
}
public void DoFoo()
{
try
{
Foo();
}
catch (ProtocolException ex)
{
/* The exception will never be caught.
Instead when in debug mode, VS2010 will warn and continue.
The deployed the app will simply crash. …Run Code Online (Sandbox Code Playgroud) c# asynchronous exception-handling task-parallel-library async-await
我读到它的任何地方都说下面的代码应该可行,但事实并非如此.
public async Task DoSomething(int x)
{
try
{
// Asynchronous implementation.
await Task.Run(() => {
throw new Exception();
x++;
});
}
catch (Exception ex)
{
// Handle exceptions ?
}
}
Run Code Online (Sandbox Code Playgroud)
也就是说,我没有抓到任何东西,并且在"投掷"线上得到一个"未处理的例外".我在这里很无能为力.
我正在尝试测试以下的http请求方法
public async Task<HttpContent> Get(string url)
{
using (HttpClient client = new HttpClient())
// breakpoint
using (HttpResponseMessage response = await client.GetAsync(url))
// can't reach anything below this point
using (HttpContent content = response.Content)
{
return content;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,调试器似乎正在跳过第二条评论下面的代码.我正在使用Visual Studio 2015 RC,有什么想法吗?我也试过检查任务窗口,什么都没看到
编辑:找到解决方案
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace ConsoleTests
{
class Program
{
static void Main(string[] args)
{
Program program = new Program();
var content = program.Get(@"http://www.google.com");
Console.WriteLine("Program finished");
}
public async Task<HttpContent> Get(string url)
{
using (HttpClient …Run Code Online (Sandbox Code Playgroud)