阻止`performSelectorInBackground:`运行两次? [英] Prevent `performSelectorInBackground:` from running twice?
问题描述
所以我使用 performSelectorInBackground:@selector(loadStuff)
在后台加载东西。这需要一些时间。
So I'm using performSelectorInBackground:@selector(loadStuff)
to load things in the background. It takes some time.
用户可能想重新加载项目,而上述方法是在后台运行。如果I performSelectorInBackground:@selector(loadStuff)
,而另一个方法已经运行,我会遇到各种错误。
The user may want to re-load the items, while the method above is running in the background. If I performSelectorInBackground:@selector(loadStuff)
again while the other method is already running, I get all kinds of errors.
有没有一种简单的方法来处理这种情况?
Is there an easy way to handle this situation?
我想停止已经运行的后台方法,然后启动新的。
I'd like to stop the already-running-in-the-background method, then start the new one. (Or if there is a better way of accomplishing the end goal, that would be fine as well).
推荐答案
如果你想要一个更好的方法来完成最终目标,要重新开始,可以取消连接并创建一个新连接。因为你要在后台线程上运行这个方法,你需要确保只有一个线程可以一次访问相关的实例变量:
If you want to start over, you can cancel the connection and create a new one. Since you're going to run this method on a background thread you need to make sure that only one thread can access the related instance variables at a time:
- (void)loadStuff
{
@synchronized(self) {
if (currentConnection != nil)
[currentConnection cancel];
[currentConnection release];
}
currentConnection = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:YES];
}
}
另一种方法是使用标志指示忙碌状态。例如,如果你想只是返回如果长期运行的方法已经在另一个线程上进行,你可以这样做:
Another way to do it is to use a flag to indicate a busy state. For example, if you wanted to just return if the long-running method were already in process on another thread, you could do this:
- (void)loadStuff
{
@synchronized(self) {
if (loadingStuff == YES)
return;
}
loadingStuff = YES;
}
NSURLRequest *request = ...
NSURLResponse *response;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningReseponse:&response error:&error];
@synchronized(self) {
loadingStuff = NO;
}
}
这篇关于阻止`performSelectorInBackground:`运行两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!