【发布时间】:2017-02-06 16:20:05
【问题描述】:
这是我的课,有异步方法和获取方法
class Webservice
{
public string token;
public async void login (string url)
{
Console.WriteLine(url);
var client = new HttpClient();
// Create the HttpContent for the form to be posted.
string username = ConfigurationSettings.AppSettings["email"];
string password = ConfigurationSettings.AppSettings["password"];
var requestContent = new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("email", username),
new KeyValuePair<string, string>("password", password),
});
// Get the response.
HttpResponseMessage response = await client.PostAsync(url, requestContent);
// Get the response content.
HttpContent responseContent = response.Content;
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
//Console.WriteLine(await reader.ReadToEndAsync());
token = await reader.ReadToEndAsync();
}
}
public string getToken (string url)
{
this.login(url);
Console.WriteLine(token);
return token+"abc";
}
令牌 = 等待 reader.ReadToEndAsync();无法设置类变量,或者getToken返回后设置,有人知道如何处理这种情况吗?
【问题讨论】:
-
不要使用
async void,这是不好的做法,使用async Task。我想你想让token静态,所以public static string token;。我猜,因为你没有说你得到什么错误信息或它发生在哪里...... -
为什么登录是异步的?如我所见,您希望在登录后立即获得结果。
-
async void仅用于事件处理程序。不能等待,这意味着您无法知道该方法是否已完成。 而不是设置字段(这是非常糟糕的做法)将签名更改为async Task<string>并返回令牌。然后你可以很容易地写var token=await login(url);并用它做任何你想做的事情
标签: c# winforms asynchronous