小编Pav*_*nov的帖子

如何从异步方法向调用者抛出异常?

今天我读了很多关于async/await的内容,这让我大吃一惊.我无法理解为什么以下测试通过.

[Test]
public void Test()
{
    var listener = new AsyncHttpListener();
    listener.ListeningAsync();

    try
    {
        new WebClient().DownloadString("http://localhost:8080/");
    }
    catch (Exception)
    {
    }

    listener.Close();
}

public class AsyncHttpListener
{
    private readonly HttpListener listener;

    public AsyncHttpListener()
    {
        listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8080/");
        listener.Start();
    }

    public void Close()
    {
        listener.Close();
    }

    public async void ListeningAsync()
    {
        var context = await listener.GetContextAsync();
        HandleContext(context);
    }

    private void HandleContext(HttpListenerContext context)
    {
        throw new Exception("test excpetion");
    }
}
Run Code Online (Sandbox Code Playgroud)


测试通过,但输出包含:

System.Exception
test excpetion
   at AsyncHttpListenerTest.AsyncHttpListener.HandleContext(HttpListenerContext context) in AsyncHttpListener.cs: line …

.net c# exception-handling async-await

8
推荐指数
1
解决办法
5304
查看次数

标签 统计

.net ×1

async-await ×1

c# ×1

exception-handling ×1