Windows Phone后台任务 - 使用HttpWebRequest或WebClient

时间:2011-09-06 13:26:33

标签: webclient httprequest windows-phone-7

我需要使用WCF向服务器发送信息。我目前正在使用WebClient通过json数据调用WCF。现在,使用后台任务,我使用json调用相同的WCF,但是从不调用UploadStringAsync的回调函数。我也尝试过HttpWebRequest,但它也没有用。

我可以在documentation中看到后台任务支持HttpWebRequest。

以下是处理WCF请求/响应的代码:

public class Communication
{
    #region Private Variables

    /// <summary>
    /// Callback method passed to MakeHttpPostRequest will be set to below variable. 
    /// This variable holds the reference to callback function and used to invoke the method passed by MakeHttpPostRequest calling method.
    /// </summary>
    private Action<string> action;

    private Action<string, object> genericAction;

    private object returnValue;

    #endregion

    #region Methods

    /// <summary>
    /// Calls WCF service using POST method.
    /// </summary>
    /// <param name="webserviceURL">URL of WCF service.</param>
    /// <param name="json">JSON data to be posted to WCF service.</param>
    /// <param name="response">Callback function that is invoked when response is received from WCF service.</param>
    public void MakeHttpPostRequest(string webserviceURL, string json, Action<string> response)
    {
        try
        {
            this.action = response;

            if (DeviceNetworkInformation.IsNetworkAvailable)
            {
                Uri uri = new Uri(webserviceURL);
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(json);

                string data = Encoding.UTF8.GetString(byteArray.ToArray(), 0, (int)byteArray.Length);
                WebClient webClient = new WebClient();
                webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(this.WebClient_UploadStringCompleted);
                webClient.Headers["Content-type"] = "application/json";
                webClient.Encoding = Encoding.UTF8;
                webClient.UploadStringAsync(uri, "POST", data);
            }
            else
            {
                if (this.action != null)
                {
                    this.action(string.Empty);
                }
            }
        }
        catch (Exception ex)
        {
            if (this.action != null)
            {
                this.action(string.Empty);
            }

            new ErrorException.ErrorException().HandleError(ex, string.Empty, Global.Modules.General);
        }
    }

    #endregion

    #region Events

    /// <summary>
    /// Callback function that gets called when response is received from web service.
    /// </summary>
    /// <param name="sender">The object that raises the event.</param>
    /// <param name="e">Object containing Http response details.</param>
    private void WebClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
    {
        try
        {
            // Check whether to invoke any method
            if (this.action != null)
            {
                // Invoke the method passed to MakeHttpPostRequest by it's calling method
                this.action(e.Result);
            }
            else if (this.genericAction != null)
            {
                // Invoke the method passed to MakeHttpPostRequest by it's calling method
                this.genericAction(e.Result, this.returnValue);
            }
        }
        catch (Exception ex)
        {
            if (this.action != null)
            {
                this.action(string.Empty);
            }

            new ErrorException.ErrorException().HandleError(ex, string.Empty, Global.Modules.General);
        }
    }

    #endregion
}

使用以下代码将json发送到服务器:

// Send location data to server
new Common.Communication().MakeHttpPostRequest(Common.ServiceURL.TrackingTracingURL, postData, result);

以上代码在应用程序中运行良好。但是,从后台任务调用时不起作用。


HttpWebRequest或WebClient没有任何问题。这是调用问题:

NotifyComplete();

由于对HttpWebRequest或WebClient的调用是异步的,因此调用NotifyComplete();在收到响应之前中止了后台任务的执行,并没有等待HttpWebRequest或WebClient响应。

有人有解决方法吗?

1 个答案:

答案 0 :(得分:3)

正如保罗在评论中提到的那样,你的后台任务很可能在25秒不活动后被终止。如果您的任务被强制终止3(?)次,它将被取消预定,直到您的应用程序再次安排它(我相信如果它继续运行它们也可以获得永久禁止,但不是我100%肯定这个)。

修改

NotifyComplete();可以在异步回调中发生。在完成响应处理后,将其移至回调的末尾。