Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 异步函数中的错误处理_C#_Asynchronous_Exception Handling_Error Handling_C# 5.0 - Fatal编程技术网

C# 异步函数中的错误处理

C# 异步函数中的错误处理,c#,asynchronous,exception-handling,error-handling,c#-5.0,C#,Asynchronous,Exception Handling,Error Handling,C# 5.0,我很难弄清楚如何正确处理异步函数中的异常。具有以下代码: static async Task NotifyPartyAsync(Uri uri, string paramName, string paramValue) { string link = string.Format("{0}?{1}={2}", uri, paramName, HttpUtility.UrlEncode(paramValue)); using (var client = new HttpClient(

我很难弄清楚如何正确处理异步函数中的异常。具有以下代码:

static async Task NotifyPartyAsync(Uri uri, string paramName, string paramValue)
{
    string link = string.Format("{0}?{1}={2}", uri, paramName, HttpUtility.UrlEncode(paramValue));
    using (var client = new HttpClient())
        try {
            using (HttpResponseMessage response = await client.GetAsync(link, HttpCompletionOption.ResponseHeadersRead))
                logger.DebugFormat("HTTP {0} from {1}", (int)response.StatusCode, link);
        }
        catch (Exception ex)    {
            logger.Error(ex);
        }
}

static void NotifyParty(Uri uri, string paramName, string paramValue)
{
    string link = string.Format("{0}?{1}={2}", uri, paramName, HttpUtility.UrlEncode(paramValue));
    using (var client = new HttpClient())
        try {
            using (HttpResponseMessage response = client.GetAsync(link, HttpCompletionOption.ResponseHeadersRead).Result)
                logger.DebugFormat("HTTP {0} from {1}", (int)response.StatusCode, link);
        }
        catch (Exception ex)    {
            logger.Error(ex);
        }
}
如何重构它,使其不重复两个函数共有的99%代码?我需要以同步和异步的方式通知uri,我不关心结果,只希望记录结果

static void NotifyParty(Uri uri, string paramName, string paramValue)
{
  await NotifyPartyAsync(uri, paramName, paramValue);
}


如果您正在使用.net 4.5或4.0,请告诉我。基于此,可能存在一些细微差别。

您应该看看这个问题:。它可能就是您想要的。

基本上,使用
async/await
您可以遵循同步编程的相同模式。除非绝对需要,否则不要在每个
async
方法中处理异常。在最顶层处理它们,即在最外层的异步或同步方法内部。此方法的功能取决于执行环境

例如,如果它是UI应用程序,则可能是一个
异步void
事件处理程序:

async Task DoWorkAsync()
{
    // don't handle exceptions here
}

async void Form_Load(object s, EventArgs args)
{
    try {
        await DoWorkAsync();
    }
    catch (Exception ex) 
    {
        // log
        logger.Error(ex);
        // report
        MessageBox.Show(ex.Message);
    }
}
或者,它可能是控制台应用程序的主入口点:

static void Main(string[] args)
{
    try {
        DoWorkAsync().Wait();
    }
    catch (Exception ex) 
    {
        // log
        logger.Error(ex);
        throw; // re-throw to terminate
    }
}
您应该了解
async
方法的异常是如何传播的。查看更多详细信息


此外,并非所有例外情况都是相同的,应该平等处理。查看Eric Lippert的。

它是.net 4.5。您的回答表明我的异步函数编写正确,但我不确定记录
响应的行。StatusCode
-它是否阻止函数在
GetAsync()
之后立即返回?在wait client.GetAsync行上,执行将返回到uber async方法的调用方。。至于'HttpResponseMessage response=wait client.GetAsync'行,它将被阻塞,因为您正在等待结果。。由于记录下一行,这是不可避免的阻塞。对于异步/等待上的控制流:
RunSynchronously()
引发“不能对未绑定到委托的任务(例如从异步方法返回的任务)调用RunSynchronously”。异常。为什么?啊,是的。。对于async/await模型,您需要使用.Wait()而不是RunSynchronously()。如果您同时拥有异步和同步API,那么您将得到大量重复的代码。希望这只是暂时的情况,因为您的代码正在变得异步。
static void Main(string[] args)
{
    try {
        DoWorkAsync().Wait();
    }
    catch (Exception ex) 
    {
        // log
        logger.Error(ex);
        throw; // re-throw to terminate
    }
}