为livetile代码添加超时?

时间:2011-11-02 18:22:20

标签: c# visual-studio-2010 windows-phone-7 live-tile

首先在这里发帖,抱歉开始提问。

在我的Windows Phone 7应用程序中,我有一个工作的动态,由后台代理触发。但是如何修改代码以便在10秒后httpwebrequest超时?

提前致谢。

protected override void OnInvoke(ScheduledTask task)
    {
        //TODO: Add code to perform your task in background

        var request = (HttpWebRequest)WebRequest.Create(
        new Uri("site.com"));

        request.BeginGetResponse(r =>
        {
            var httpRequest = (HttpWebRequest)r.AsyncState;
            var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);
            using (var reader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var response = reader.ReadToEnd();

                Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    string strResult = response;


                    /// If application uses both PeriodicTask and ResourceIntensiveTask
                    if (task is PeriodicTask)
                    {
                        // Execute periodic task actions here.
                        ShellTile TileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("TileID=2"));
                        if (TileToFind != null)
                        {

                            StandardTileData NewTileData = new StandardTileData
                            {
                                BackgroundImage = new Uri("Pin-to-start.png", UriKind.Relative),
                                Title = strResult,
                                Count = null
                            };
                            TileToFind.Update(NewTileData);
                        }
                    }
                    else
                    {
                        // Execute resource-intensive task actions here.
                    }

                    NotifyComplete();
                }));
            }
        }, request);
    }

2 个答案:

答案 0 :(得分:3)

以下是我在其中一个应用中使用的代码中的复制/粘贴。它将在60秒后中止连接。

    private static void DoWebRequest(string uri)
    {
        string id = "my_request";

        Timer t = null;
        int timeout = 60; // in seconds

        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Accept = "*/*";
            request.AllowAutoRedirect = true;

            // disable caching.
            request.Headers["Cache-Control"] = "no-cache";
            request.Headers["Pragma"] = "no-cache";

            t = new Timer(
                state =>
                {
                    if (string.Compare(state.ToString(), id, StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        logger.Write("Timeout reached for connection [{0}], aborting download.", id);

                        request.Abort();
                        t.Dispose();
                    }
                },
                id,
                timeout * 1000,
                0);

            request.BeginGetResponse(
                r =>
                {
                    try
                    {
                        if (t != null)
                        {
                            t.Dispose();
                        }

                        // your code for processing the results

                    }
                    catch
                    {
                        // error handling.
                    }
                },
                request);
        }
        catch
        {
        }
    }

答案 1 :(得分:2)

  

但是我如何修改代码以便在10秒后httpwebrequest超时?

你的意思是它会在不考虑超时的情况下调用NotifyComplete()吗? - )问题是15秒后任务终止,并被禁用,直到用户重新启动(在你的应用程序内)。 / p>

我建议使用TPL for Silverlight并利用使用任务设置超时的功能。

类似的东西:

protected override void OnInvoke(ScheduledTask task)
{
    var fetchTask = FetchData(TimeSpan.FromSeconds(10));
    fetchTask.ContinueWith(x =>
    {
        Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
        {
            string strResult = x.Result; // mind you, x.Result will be "null" when a timeout occours.

            ...

            NotifyComplete();
        }));
    });
}

private Task<string> FetchData(TimeSpan timeout)
{ 
    var tcs = new TaskCompletionSource<string>();
    var request = (HttpWebRequest)WebRequest.Create(new Uri("site.com"));

    Timer timer = null;
    timer = new Timer(sender =>
    {
        tcs.TrySetResult(null);
        timer.Dispose();
    }, null, (int)timeout.TotalMilliseconds, Timeout.Infinite);

    request.BeginGetResponse(r =>
    {
        var httpRequest = (HttpWebRequest)r.AsyncState;
        var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);
        using (var reader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var response = reader.ReadToEnd();
            tcs.TrySetResult(response);
        }
    });

    return tcs.Task;
}