How to Kill/Stop a background thread?

你。 提交于 2019-11-27 08:04:14

问题


So I have a method that performs a loop and because of the way my program works i'm calling this method using,

[self performSelectorInBackground:@selector(myMethod:) withObject:arg];

And the method itself,

- (void)myMethod:(id)arg {
    //...

    for (//Loop Conditions) {
        if (stopMorse) {
            break;
        }
        //Do stuff
    }

    //...
}

Now I would like to allow the user to stop this loop from running, so is there a way of killing/stopping the thread.

I've tried adding a BOOL but the problem is that it doesn't seem to get updated because it's on a separate thread. What is the best way to stop this loop from running?


回答1:


You shouldn't forcibly kill/stop the thread for reasons outlined in this answer to a similar question, and this answer to another similar question.

It should be possible to check a boolean as you are doing, and there shouldn't be a problem with another thread setting the value of the boolean. Can you post the code that is attempting to set the boolean?



来源:https://stackoverflow.com/questions/4149656/how-to-kill-stop-a-background-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!