从回报中获取对象

问题描述 投票:0回答:1

我有一个使用任务返回的异步函数。我希望能够得到结果对象,但我得到了错误:这是我的代码。

public async Task<User> getResponse(string username, string password) {

....

return user;

}

public void callResponse()

{

var response = getResponse(uname, pass);

while(!response.isCompleted);

User user = response.Result;

}

然而,它说 "FormatException: Input string was not in correct format.)

有什么办法吗?

httpresponse
1个回答
0
投票

当你调用一个异步函数时,使用 await。这意味着你需要让 callResponse 也成为异步函数,并在任何时候调用它时都要等待它。

如果由于某种原因,你不能使 callResponse 方法成为异步的,就使用 getResponse(uname, pass).GetAwaiter().GetResult()。这是避免死锁或线程饥饿的唯一正确方法。如果你使用.Wait,你会造成死锁。如果使用.Result,可能会导致线程饥渴

© www.soinside.com 2019 - 2024. All rights reserved.