我有多功能的课程。在该类中我称之为Web服务的两个函数,第一个Web服务函数正常工作。但是第二个Web服务方法不等待服务的响应它可以自动调用另一个服务 我用过了
let saveSemaphore = dispatch_semaphore_create(0) as dispatch_semaphore_t
let count = arrDeleteExecutionDetails.count
for (index, object) in arrDeleteExecutionDetails.enumerate()
{
Common.checklistExecute = object
let request = "\(Common.webServiceURL!)/ProInspectorJson.svc/DeleteExecutionDetails?pExecutionDetailsId=\(object.id_ExecutionDetails!)"
let webservice = WebServiceCall(url: request, delegate: self)
webservice.webServiceGetMethod(request)
if index != count-1
{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}
else
{
dispatch_semaphore_signal(semaphore)
}
上述方法正常工作
for checklistExecution in arrExecutionDetails
{
Common.checklistExecute = checklistExecution
let request = "\(Common.webServiceURL!)/ProInspectorJson.svc/SaveExecutionV3?scheduleID=\(checklistExecution.id_Agendamentor!)&userID=\(Common.userId!)&ID_PI_ChecklistConfiguration=\(checklistExecution.id_ChecklistConfig!)&Observations=\(checklistExecution.observation!)&ID_PI_tblMastRiskFactor=\(checklistExecution.id_RiskFactor!)&CorrectiveAction=\(checklistExecution.correctiveActions!)&ID_PI_FormulaResultsHeader=0&Longitude=0&Lattitude=0&checklistExecutionId=\(checklistExecution.id_ExecutionDetails!)&ErrorCode=0&ID_PI_ObjectSubCategory=\(checklistExecution.objectSubCategory!)"
let webservice = WebServiceCall(url: request, delegate: self)
webservice.webServiceGetMethod(request)
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}
但第二个不工作
for
循环有5个元素,同时调用5个元素。它不是在等待第一次服务响应。
dispatch_semaphore_signal(semaphore)
我完全打电话。
答案 0 :(得分:1)
你的第一个例子在循环的最后一次迭代中没有执行dispatch_semaphore_wait
,而是奇怪地发出了另一个dispatch_semaphore_signal
。假设您的代表总是发出信号,您最终会发现信号量信号不匹配。
因此,如果您在第二个示例中使用相同的信号量,您可能最终会得到两个额外的信号(不仅仅是您在第一个示例中for
循环中发出的信号index
1}}是count - 1
,但可能是委托方法的最后一次迭代也可能发出了一个不满意的信号),因此第二个循环中的三个请求将同时运行。
使用此信号量模式时,请确保每个“信号”与“等待”匹配。如果你在每个“信号”和“等待”中添加print
语句,这些不平衡的呼叫将跳出你(而不是看到交替的“等待”和“信号”呼叫,你会看到一系列的“signal”连续调用(在这种情况下,在第一个for
循环结束时))。
最重要的是,您可能希望删除if index == count-1 { ... }
支票,只需dispatch_semaphore_wait
。如果委托方法中有一些奇怪的东西需要一些逻辑,你应该编辑你的问题,告诉我们你为什么使用你所做的逻辑。
更好的是,你真的应该完全删除这些信号量的代码,而是采用异步模式。编写同步代码感觉非常直观,但它实际上是低效的(阻塞线程;失去并发请求的巨大好处;等等)和有问题(容易死锁;绝不应该从主线程完成;等等)。您应该接受异步模式,例如调度组或NSOperation
依赖项。