I have this piece of code in my Windows Store app where I handle a button click. But somehow, UI freezes when I click this button on rare occasion. It mostly happens when I connect to a Wi-Fi network further away than the one I usually connect to. Taking into consideration that I download a RSS feed from the internet, it is most probably related to my using of async/await keywords. If I correctly understood the mechanics of async/await, UI thread should not block at all. Am I missing something here?
private async void Add_Click(object sender, RoutedEventArgs e)
{
AddButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
DownloadProgressRing.Visibility = Windows.UI.Xaml.Visibility.Visible;
DownloadProgressRing.IsActive = true;
RssData rssData = App.Current.Resources["rssData"] as RssData;
Uri uri = FixUrl(RssUrl.Text);
if (uri != null)
{
newRssFeed = new RssFeed(uri.ToString());
Task<bool> success = newRssFeed.RetrieveFeed();
if (await success)
{
SubmitButtonPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;
FeedTitleTextBox.Text = newRssFeed.Title == null ? String.Empty : newRssFeed.Title;
}
}
}
Constructor for RssFeed:
public RssFeed(string url)
{
Url = url;
}
RetrieveFeed function:
public async Task<bool> RetrieveFeed()
{
if (Url != null)
{
try
{
SyndicationClient sc = new SyndicationClient();
SyndicationFeed sf = await sc.RetrieveFeedAsync(new Uri(Url, UriKind.Absolute));
if (sf != null)
{
ValidateAndInitFeed(sf);
return true;
}
}
catch (Exception ex)
{
}
}
return false;
}
private void ValidateAndInitFeed(SyndicationFeed feed)
{
if (feed.Title != null)
Title = feed.Title.Text;
if (feed.ImageUri != null)
Image = feed.ImageUri.ToString();
if (feed.Subtitle != null)
Subtitle = feed.Subtitle.Text;
}
Try calling
RetrieveFeed()
on a background thread. Perhaps processing the request or response is what takes a lot of time and if it is started on UI thread - it will run on UI thread.I've the same issue on some of my Windows Phone apps and I don't have any good explanation, the only good one is the same that Killercam referred.
When you call an async method it doesn't return immediately (I assume that the methods aren't something like
return Task.Factory.StartNew(...);
), it does some work, sets the callback and then returns, if the work that it makes has anything related to network connections, in a slow connection this can block the function.A good way to test this symptoms is connect to a router with wifi and then disconnect the router from the internet, you will have the same behavior that you are describing.
The use of the
async
/await
look okay. You reference a distant Wi-Fi connection, this may be purely down to a weak signal, hence poor bandwidth.I hope this helps.