我想在iPhone上的背景下運行一個任務。我從performSelectorInBackground
開始。我還在主線程上創建NSTimer
,以檢查是否正常工作。我預計,而另一個線程做這件事的計時器將運行:爲什麼NSTimer在另一個線程運行時被阻塞?
- (void)viewDidLoad
{
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self
selector:@selector(onTimerEvent:)
userInfo:nil repeats:YES];
[self performSelectorInBackground:@selector(lengthyMethod) withObject:nil];
NSLog(@"Here we go!");
}
- (void)onTimerEvent:(NSTimer *)timer
{
NSLog(@"timer!");
}
的lenghtyMethod
執行的東西很多,包括使用ASIHTTPRequest等
從NSLog
輸出看起來是這樣的網址下載:
2011-03-11 15:17:07.470 MyApp[6613:207] Here we go!
2011-03-11 15:17:07.570 MyApp[6613:207] timer!
2011-03-11 15:17:07.670 MyApp[6613:207] timer!
// ... several seconds of output from lenghtyMethod omitted ...
2011-03-11 15:17:11.075 MyApp[6613:207] timer!
2011-03-11 15:17:11.170 MyApp[6613:207] timer!
// ... etc ... timer runs as expected when the call is completed ...
的問題是,後臺線程似乎要禁止定時器。我對此的理解是,performSelectorInBackground應該在與主循環分開的新線程中運行。
我不明白這一點。線程正在運行時,定時器沒有輸出。一旦通話完成,計時器將再次開始記錄。
爲了記錄,線程主要是做I/O(加載URL),所以OS應該有足夠的時間來切換線程。這發生在模擬器和實際設備上。
確保longyMethod不會對UI進行任何調用,並檢查您是否使用ASIHTTPRequest的異步方法。 – David 2011-03-11 14:48:33
@Johny Grass:ASIHTTPRequest確實是異步的。但是,這很重要,它已經在後臺線程中運行了。 – 2011-03-11 15:25:17
我敢打賭,有'ASIHTTPRequest'完成處理程序正在發生。看起來他們阻止了計時器。咦?奇怪的。 – 2011-03-11 15:40:10