Cannot cancel thread

I’m getting an error when trying to cancel a task

crewData.Task = task.delay(TimeToAttack, function()
	while crewData.Target == SelectedTarget do
		local Alive = GameService:Attack(player, SelectedTarget, crewId)

		if not Alive then -- NPC died
			self:Recall(player)

			break
		end

		task.wait(1)
	end
end)

-- later on
if crewData.Task then
	task.cancel(crewData.Task) -- ERROR
end
2 Likes

You should probably be using coroutines or a boolean to check the status of the thread, and then close it.

1 Like

You just have to find the cause by commenting out certain parts of the code.
For example, after commenting something out I can be sure that the thread is cancelled correctly, so, in your case, that is not the problem.

1 Like

If you get an error, you have to say what it is on the devforum.

1 Like

image

print(coroutine.status(SpawnedCrew[crewId].Task))
task.cancel(SpawnedCrew[crewId].Task)

Says it’s running beforehand

1 Like

The error is in the title. That’s what the exact error message says

1 Like

it’s a roblox studio bug (task.cancel basically cancels the thread, which it is, but for some reason it can’t), use a coroutine instead

1 Like

It might be the case that the thread has died before using task.cancel

An easy fix would be to use coroutine.close instead, which doesn’t error if you attempt to close a dead thread but rather returns false and a string value containing the error message

1 Like