首先我的代码:
private CLGeocoder _coder = new CLGeocoder();
private void TestWithTpl()
{
Console.WriteLine("Test started");
var testLocation = new CLLocation(52.268157,-1.4209);
Task.Factory.StartNew(async () =>
{
for (var i=0; i < 100; i++)
{
Console.WriteLine("Starting iteration {0}", i);
var res = await _coder.ReverseGeocodeLocationAsync(testLocation);
Console.WriteLine(res[0].AdministrativeArea);
Console.WriteLine("Finished iteration {0}", i);
}
});
Console.WriteLine("Finished");
}
private void TestDefault()
{
Console.WriteLine("Test started");
var testLocation = new CLLocation(52.268157,-1.4209);
Task.Factory.StartNew(() =>
{
for (var i=0; i < 100; i++)
{
Console.WriteLine("Starting iteration {0}", i);
var res = _coder.ReverseGeocodeLocationAsync(testLocation).Result;
Console.WriteLine(res[0].AdministrativeArea);
Console.WriteLine("Finished iteration {0}", i);
}
});
Console.WriteLine("Finished");
}
如您所见,TestWithTpl 将使用 async 和 await,而 TestDefault 仅使用 ReverseGeocodeLocationAsync 的结果。
无论我使用哪种方法:输出将是这样的:
2013-10-11 12:05:54.882 AddressResolveTest[5290:a0b] Test started
Thread started: <Thread Pool> #3
Thread started: <Thread Pool> #4
2013-10-11 12:05:54.892 AddressResolveTest[5290:a0b] Finished
2013-10-11 12:05:54.897 AddressResolveTest[5290:6303] Starting iteration 0
2013-10-11 12:05:55.125 AddressResolveTest[5290:6303] England
2013-10-11 12:05:55.126 AddressResolveTest[5290:6303] Finished iteration 0
2013-10-11 12:05:55.127 AddressResolveTest[5290:6303] Starting iteration 1
...
2013-10-11 12:05:57.302 AddressResolveTest[5290:6303] Finished iteration 49
2013-10-11 12:05:57.302 AddressResolveTest[5290:6303] Starting iteration 50
在最后一行之后没有任何反应。
我不知道,为什么:
- “完成”是在代码准备好之前编写的。
- 代码总是在请求号处停止。50.