httpRequest暂时冻结我的应用程序

时间:2012-08-14 07:54:30

标签: c# .net wpf oauth httprequest

好的,在我继续之前,让我说明我的背景是在网页脚本中;所以申请对我来说很陌生。我对.NET知之甚少,而且因为我的知识有限,我一直在滑冰。

无论如何,在我的应用程序中,我有一个OAuth httpRequest。请求本身工作正常,它从Web API获取我需要的数据。但问题是,每当我单击激活请求的按钮时,我的程序会冻结几秒钟,直到请求完成。我还有另一个请求,每60秒自动完成一次。这当然意味着每60秒,我的程序会冻结几秒钟。如何解决这个问题?

    private string twitchCallAPI(string accessKey, string accessSecret, string endpointURI, string httpMethod)
    {
        OAuthHttpWebRequest httpRequest = new OAuthHttpWebRequest();
        httpRequest.ConsumerToken = new OAuthToken { Token = this.twitchConKey, TokenSecret = this.twitchConSecret };
        httpRequest.Token = new OAuthToken() { Token = accessKey, TokenSecret = accessSecret };
        httpRequest.SetUri(endpointURI);
        httpRequest.Method = httpMethod;

        try
        {
            using (var response = httpRequest.GetResponse())
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    return reader.ReadToEnd();
                }
            }
        }
        catch (WebException ex)
        {
            using (var reader = new StreamReader(ex.Response.GetResponseStream()))
            {
                System.Windows.MessageBox.Show(reader.ReadToEnd());
            }
        }
        catch (Exception ex)
        {
            System.Windows.MessageBox.Show(ex.ToString());
        }

        return string.Empty;
    }

5 个答案:

答案 0 :(得分:3)

您可以使用background worker

答案 1 :(得分:2)

简要地说,请在任务中请求并使用UI同步上下文更新UI线程

TaskFactory.StartNew(()=>
{
    //do web request
})
.ContinueWith(() =>
{
    this.TextBlock1.Text = "Complete"; 
}, TaskScheduler.FromCurrentSynchronizationContext());

答案 2 :(得分:1)

您可以尝试使用Async方法,即使用其他线程等待请求的响应。它是一个你可以探索的解决方案。

http://msdn.microsoft.com/en-us/library/86wf6409%28v=vs.100%29.aspx

答案 3 :(得分:1)

您可以使用await关键字:

private async void OnButtonClick()
{
   TextBox.Text = await twitchCallAPIAsync(accessKey, accessSecret, endpointURI, httpMethod);
}

答案 4 :(得分:0)

这样做的主要原因是您的应用程序正在等待您启动的方法完成。你必须看看'异步'的概念。

执行'async'方法的程序会继续其工作流程,并且不会等待该方法产生结果。