1

I have the following code to read feeds

XmlReader reader = XmlReader.Create(url)
SyndicationFeed feed = SyndicationFeed.Load(reader)

I have to account for instances when the internet is not working. I noticed that whenever wifi is off, the code is paused at the Load(reader).

Since there's technically no error, I can't catch the code.

If wifi is not enabled, I do not want to load the reader with SyndicationFeed. Should I use a timer? What would be the best way to do this?

lost9123193
  • 10,460
  • 26
  • 73
  • 113
  • I think that if you leave it enough time, at the end it will throw an exception about not reaching the remote url. If you want a faster way of cancelling when it's not available then you can download manually the content of the url using HttpClient or HttpWebRequest and setting a low timeout, then you can create the XmlReader with the downloaded string. – Gusman May 30 '18 at 20:39

1 Answers1

2

There are a few ways to do this. One way is to make the slow bit asynchronous and then add a timeout to the task.

This also has the advantage of not blocking the UI whilst performing the Operation.

As the API isn't inherently asynchronous you will have to wrap it yourself.

Here's some sample code I have that works:

async Task Main()
{
    //Normal speed
    var feed = await GetFeed("https://taeguk.co.uk/feed/");
    Console.WriteLine(feed);

    //Too Slow = null
    feed = await GetFeed("http://www.deelay.me/2000/https://taeguk.co.uk/feed/");
    Console.WriteLine(feed);
}

async Task<SyndicationFeed> GetFeed(String url)
{
    var task = Task.Factory.StartNew(() =>
            {
                XmlReader reader = XmlReader.Create(url);
                return SyndicationFeed.Load(reader);
            });

    int timeout = 1000;
    if (await Task.WhenAny(task, Task.Delay(timeout)) == task)
    {
        return await task;
    }
    else
    {
        return null;
    }
}
johnny 5
  • 19,893
  • 50
  • 121
  • 195
DaveShaw
  • 52,123
  • 16
  • 112
  • 141