让应用程序等到Variables更新

时间:2014-01-06 03:57:27

标签: c# oauth

我目前正在与OAuth合作。当前代码的问题是它不会等到用户允许网站上的应用程序并获得正确的密钥和秘密。我正在使用线程类型等待,但有时它不够长......有些用户比其他用户慢。我附上了我的代码片段。我想知道的是在哪里插入while语句,或者我应该使用它?

public OAuthToken GetRequestToken(Uri baseUri, string consumerKey, string consumerSecret)
{
    var uri = new Uri(baseUri, "oauth/request_token");
    uri = SignRequest(uri, consumerKey, consumerSecret);
    var request = (HttpWebRequest) WebRequest.Create(uri);
    request.Method = WebRequestMethods.Http.Get;
    var response = request.GetResponse();
    var queryString = new StreamReader(response.GetResponseStream()).ReadToEnd();
    var parts = queryString.Split('&');
    var token = parts[1].Substring(parts[1].IndexOf('=') + 1);
    var secret = parts[0].Substring(parts[0].IndexOf('=') + 1);
    return new OAuthToken(token, secret);
} 

2 个答案:

答案 0 :(得分:3)

您应该立即切换到.NET附带的较新的 System.Net.Http System.Net.Http.WebRequest 库。这些都使用.NET 4.5提供的新异步编程。

您可以调用请求(返回您可以等待的任务对象)并自动暂停响应的线程。用户界面不会像往常一样做出回应。如果您不了解新的异步和等待关键字是如何工作的,那么这可能是最简单的事情。有关它们的更多信息,请参阅http://msdn.microsoft.com/en-us/library/hh191443.aspx

以下是使用新库执行操作的代码:

using System.Net.Http;

public OAuthToken GetRequestToken(Uri baseUri, string consumerKey, string consumerSecret)
{
    var uri = new Uri(baseUri, "oauth/request_token");
    uri = SignRequest(uri, consumerKey, consumerSecret);

    var message = new HttpRequestMessage(new HttpMethod("GET"), uri);
    var handler = new WebRequestHandler();
    var client = new HttpClient(handler);

    // Use the http client to send the request to the server.
    Task<HttpResponseMessage> responseTask = client.SendAsync(message);

    // The responseTask object is like a wrapper for the other task thread.
    // We can tell this task object that we want to pause our current thread
    // and wait for the client.SendAsync call to finish.
    responseTask.Wait();

    // - Once that thread finishes, and the code continues on, we need to 
    //   tell it to read out the response data from the backing objects. 
    // - The responseTask.Result property represents the object the async task 
    //   was wrapping, we want to pull it out, then use it and get the content 
    //   (body of the response) back. 
    // - Getting the response actually creates another async task (the 
    //   .ReadAsStringAsync() call) but by accessing the .Result
    //   property, it is as if we called .ReadAsStringAsync().Wait(); Except that
    //   by using Result directly, we not only call Wait() but we get the resulting, 
    //   wrapped object back. Hope that didn't confuse you much :)
    var queryString = responseTask.Result.Content.ReadAsStringAsync().Result;

    // And all your other normal code continues.
    var parts = queryString.Split('&');
    var token = parts[1].Substring(parts[1].IndexOf('=') + 1);
    var secret = parts[0].Substring(parts[0].IndexOf('=') + 1);
    return new OAuthToken(token, secret);
} 

答案 1 :(得分:0)

为什么不使用模式弹出,然后在提交按钮

上调用身份验证类