首先是我的代码:
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
在最后一行之后没有任何反应。
我不知道,为什么:
答案 0 :(得分:4)
“完成”应该在开始时打印,至少对于TPL版本,因为StartNew()
在后台启动任务,并继续执行。 “默认”版本不应该是这种情况。你能查一下吗?
问题是StartNew()吞下异常。如果你改变你的代码:
Console.WriteLine("Test started");
var testLocation = new CLLocation(52.268157,-1.4209);
Task.Factory.StartNew(async () =>
{
try{
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);
}
}catch(Exception e){
Console.WriteLine (e);
}
});
Console.WriteLine("Finished");
您将能够通过以下消息获取Exception
:The operation couldn’t be completed. (kCLErrorDomain error 2.)
谷歌搜索此消息会在stackoverflow上获得大量点击,例如1和2。 This answer甚至宣布你获得相同的“50”限制。
最后,我会说Apple限制你每分钟可以做的请求数量,甚至是recommend you not to overuse the API:
应用程序应该意识到它们如何使用地理编码。这是 有效使用此类的一些经验法则:
最多为一个用户操作发送一个地理编码请求。
希望它有所帮助。