简体   繁体   English

异步方法中的目标调用异常

[英]Target Invocation Exception in async method

I am trying to retrieve items from an rss feed but at times I get a TargetInvocationException 'unable to connect to remote server'. 我试图从rss提要中检索项目,但有时会收到TargetInvocationException'无法连接到远程服务器'。 I am trying to use a try catch block to catch this error but I am not managing as I need the variable feed to be used throughout the other code and like this it is not visible. 我正在尝试使用try catch块来捕获此错误,但是我没有进行管理,因为我需要在其他代码中使用变量供稿,并且这样不可见。 Any suggestions? 有什么建议么?

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;
    }

 }
}

This kind of error cannot be prevented. 无法避免这种错误。 It is an exogenous exception . 这是一个外生的例外

There is only one way to deal with those kinds of errors: your application must be designed to expect them and react in a reasonable way (eg, bring up an error dialog or notification). 处理这些类型的错误只有一种方法:您的应用程序必须设计成期望它们并以合理的方式做出反应(例如,显示错误对话框或通知)。

In particular, don't try to ignore them with an empty catch block. 特别是,不要试图用空的catch块忽略它们。

IAsyncOperationWithProgress<SyndicationFeed, RetrievalProgress> feed;

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM