【问题标题】:Target Invocation Exception in async method异步方法中的目标调用异常
【发布时间】:2014-02-02 11:11:17
【问题描述】:

我正在尝试从 rss 提要中检索项目,但有时我会收到 TargetInvocationException '无法连接到远程服务器'。我正在尝试使用 try catch 块来捕获此错误,但我没有进行管理,因为我需要在整个其他代码中使用变量提要,并且像这样它是不可见的。有什么建议吗?

public static async Task<List<FeedItem>> getFeedsAsync(string url)
    {
       //The web object that will retrieve our feeds..
       SyndicationClient client = new SyndicationClient();

       //The URL of our feeds..
       Uri feedUri = new Uri(url);

       //Retrieve async the feeds..
       try
       {
           var feed = await client.RetrieveFeedAsync(feedUri);
       }
       catch (TargetInvocationException e)
       {

       }

       //The list of our feeds..
       List<FeedItem> feedData = new List<FeedItem>();

       //Fill up the list with each feed content..
       foreach (SyndicationItem item in feed.Items)
       {
             FeedItem feedItem = new FeedItem();
             feedItem.Content = item.Summary.Text;
             feedItem.Link = item.Links[0].Uri;
             feedItem.PubDate = item.PublishedDate.DateTime;
             feedItem.Title = item.Title.Text;

             try
             {
                 feedItem.Author = item.Authors[0].Name;
             }
             catch(ArgumentException)
             { }

             feedData.Add(feedItem);
         }

         return feedData;
    }

 }
}

【问题讨论】:

    标签: c# async-await server-error targetinvocationexception


    【解决方案1】:

    这种错误是无法避免的。这是一个exogenous exception

    只有一种方法可以处理这些类型的错误:您的应用程序必须设计为预期它们并以合理的方式做出反应(例如,显示错误对话框或通知)。

    特别是,不要试图用空的catch 块来忽略它们。

    【讨论】:

    • 如何显示来自 catch 块的弹出对话框?
    • 您可以使用平台上可用的任何 API。
    【解决方案2】:
    IAsyncOperationWithProgress<SyndicationFeed, RetrievalProgress> feed;
    
    //Retrieve async the feeds..
    try
    {
       feed = await client.RetrieveFeedAsync(feedUri);
    }
    catch (TargetInvocationException e)
    {
    
    }
    

    【讨论】:

    • 如果我使用它,我会收到一个错误,我无法从 Windows.Web.Syndication.SyndicationFeed 转换为 Windows.Foundation。 IAsyncOperationWithProgress
    • @TamaraCaligari 您应该使用RetrieveFeedAsync 返回的特定类型。您似乎遇到了“使用”问题,因此请尝试使用完整的限定名称。
    猜你喜欢
    • 2016-10-13
    • 2012-01-01
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    相关资源
    最近更新 更多