【发布时间】:2014-07-13 23:42:32
【问题描述】:
我正在为 Mono 编写一个控制台应用程序,试图让 HttpClient 下载一些内容并使用 Json.NET 对其进行反序列化。
我遇到的问题是调用异步方法时出现堆栈溢出。
它是这样的,简化为问题的核心:
public static void Main(string[] args){
...
Manager man = new Manager(){...}; // setting up target url, timeouts etc
man.RenewAuth().Wait(); //it's async but the first time it runs synchronously
...
}
public class Manager{
...
async Task<T> GetAsync<T> (string urlAdd)
{
var httpRes = await Client.GetAsync (Client.BaseAddress + urlAdd);
string s = await httpRes.Content.ReadAsStringAsync ();
var deserialized = JsonConvert.DeserializeObject<T> (s);
return deserialized ;
}
public async Task RenewAuth () //
{
... // logging in, setting up etc
// THIS WORKS:
var aKey = GetAsync<AuthKey> ("/AuthKey?email=" + email).Result;
// THIS DOESN'T WORK, CAUSES STACK OVERFLOW:
var aKey = await GetAsync<AuthKey> ("/AuthKey?email=" + email);
... // store the api auth key from aKey and return
}
}
在控制台中我得到了这个:
Stack overflow in unmanaged: IP: 0x9a823e19, fault addr: 0xb0221ffc
Stack overflow in unmanaged: IP: 0x93b36482, fault addr: 0xb0220ff4
Stack overflow in unmanaged: IP: 0x93b36482, fault addr: 0xb021fff4
Stack overflow in unmanaged: IP: 0x93b3388a, fault addr: 0xb021effc
Stack overflow in unmanaged: IP: 0x93b36482, fault addr: 0xb021dff4
Stack overflow in unmanaged: IP: 0x93b36482, fault addr: 0xb021cff4
Stack overflow in unmanaged: IP: 0x93b3388a, fault addr: 0xb021bffc
Stack overflow in unmanaged: IP: 0x93b36482, fault addr: 0xb021aff4
Stack overflow: IP: 0x9a823e19, fault addr: 0xb0218ffc
Stacktrace:
Press any key to continue...
【问题讨论】:
-
什么是 Mono 运行时版本?您是否尝试过最新的开发分支?此外,您应该将其确定为
Client.GetAsync或Content.ReadAsStringAsync。 -
单声道版本是 Xamarin 的最新测试版附带的,我希望它是最新的。实际的异步调用无关紧要 - 我尝试了多种组合,但在不起作用的行之后仍然无法命中断点
-
public async Task RenewAuth (){ var aKey = GetAsync<AuthKey> (\*...*\).Result;不要这样做!!!!不要在使用Async的同一代码中使用.Result,它将在控制台程序中工作,但会死锁任何具有 SynchronizationContext 的东西(除了控制台应用程序之外的几乎其他任何东西) -
@ScottChamberlain 谢谢,斯科特!我确实在不同的环境中通过在 Xamarin.Forms 中显示 ActionsList 而没有 async 或在命令中使用 .Wait() 或 .Result 发现了这一点 - 操作根本不显示。但是,这纯粹是出于故障排除目的
标签: c# mono task-parallel-library async-await stack-overflow