我有一个串行队列,我在其中同步添加任务。这是为了防止从多个点同时调用相同的函数。
这是我的代码:
var isProcessGoingOn = false
let serialQueue = DispatchQueue(label: "co.random.queue")
func funcA() {
serialQueue.sync {
if isProcessGoingOn {
debugPrint("Returned")
return
} else {
isProcessGoingOn = true
debugPrint("Executing Code")
// This is to mock the n/w call behaviour. In actual code, I would have a n/w hit in this place.
serialQueue.asyncAfter(deadline: .now() + .seconds(2), execute: {
debugPrint("Setting isProcessGoingOn false")
isProcessGoingOn = false
funcA()
//There may be some cases, where I would need to call the funcA from here.
})
}
}
}
现在,让我们假设该函数被调用两次:
funcA()
funcA()
我得到以下输出:
"Executing Code"
"Returned"
现在我期待第三次打电话到funcA,但我没有得到。 谁能解释一下这里的问题是什么?
提前致谢。
答案 0 :(得分:0)
根据您的代码,您的第一个方法调用将执行 floatingBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
return view;
}
并设置debugPrint("Executing Code")
,同时您再次调用方法funcA(),所以它不等你的嵌套块是:
isProcessGoingOn = true
因此,由于serialQueue.asyncAfter(deadline: .now() + .seconds(2), execute: {
debugPrint("Setting isProcessGoingOn false")
isProcessGoingOn = false
funcA()
})
代码,上面的块永远不会执行。因为它将等待2秒,并且在此代码执行之前,您的第二个方法调用将执行deadline: .now() + .seconds(2)
并从方法返回。
<强>解决方案:强>
您需要从嵌套块中移除2秒延迟。
<强>缺点:强>
这会影响您的方法调用第二次。它会显示执行中断的错误。
我希望这会对你有所帮助,你会得到答案。