【发布时间】:2014-08-06 18:58:51
【问题描述】:
我在使用 HttpClient 和 Timers 时遇到了一个奇怪的问题。我有大量对象(最多 10,000 个)发布到 Web 服务。这些对象在计时器上,并在创建后的某个时间发布到服务。问题是 Post 会停止,直到所有计时器都启动。有关示例,请参见下面的代码。
问:为什么 Post 会挂起,直到所有 Timer 都开始?如何修复它以使帖子在其他计时器启动时正常运行?
public class MyObject
{
public void Run()
{
var result = Post(someData).Result;
DoOtherStuff();
}
}
static async Task<string> Post(string data)
{
using (var client = new HttpClient())
{
//Hangs here until all timers are started
var response = await client.PostAsync(new Uri(url), data).ConfigureAwait(continueOnCapturedContext: false);
var text = await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false);
return text;
}
}
static void Main(string[] args)
{
for (int i = 0; i < 1000; i++)
{
TimeSpan delay = TimeSpan.FromSeconds(1);
if (i % 2 == 0) delay = TimeSpan.FromDays(1);
System.Timers.Timer timer = new System.Timers.Timer();
timer.AutoReset = false;
timer.Interval = delay.TotalMilliseconds;
timer.Elapsed += (x, y) =>
{
MyObject o = new MyObject();
o.Run();
};
timer.Start();
}
Console.ReadKey();
}
【问题讨论】:
标签: c# async-await c#-5.0 dotnet-httpclient