在后台循环后运行代码结束

时间:2016-05-30 04:28:50

标签: xcode swift multithreading

我在while循环中运行后台线程,我在做一些文件处理任务。循环后我有一些代码。但是在循环结束之前循环执行后的代码(因为我使用的是后台线程)。有什么办法可以在循环结束后完全执行一些代码吗?

这是我的代码:

while i < testCount {
    let task = AsyncTask(
        backgroundTask: {
            () -> Double in
            // some file handling
            return 234.09

        },
        afterTask: {
            (val: Double) in
            self.showVal(val)
        }
    );
    task.execute();

    i += 1
}

// I want to run this code after the loop ends
print("average: \(avg)")
showVal(avg)

我的showVal(Double)功能

func showVal(val: Double) {
    print("val found: \(val)")
    display.text = "\(val) found"
}

这是我的AsyncTask

public class AsyncTask <BGParam,BGResult>{
    private var pre:(()->())?;//Optional closure -> called before the backgroundTask
    private var bgTask:(param:BGParam)->BGResult;//background task
    private var post:((param:BGResult)->())?;//Optional closure -> called after the backgroundTask

    public init(beforeTask: (()->())?=nil, backgroundTask: (param:BGParam)->BGResult, afterTask:((param:BGResult)->())?=nil){
        self.pre=beforeTask;
        self.bgTask=backgroundTask;
        self.post=afterTask;
    }

    public func execute(param:BGParam){
        pre?()//if beforeTask exists - invoke it before bgTask
        dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {
            let bgResult=self.bgTask(param: param);//execute backgroundTask in background thread
            if(self.post != nil){//if afterTask exists - invoke it in UI thread after bgTask
                dispatch_async(dispatch_get_main_queue(),{self.post!(param: bgResult)});
            }
        });
    }
}

注意:我是Swift的初学者。

修改 我其实想做:

  1. 后台文件处理任务
  2. 任务结束后,我想在UILabel中显示文字
  3. 我需要多次执行这两项任务(比如说100次)。如果swift有更方便的方法,请告知。

1 个答案:

答案 0 :(得分:0)

我会根据我们的讨论尝试使用一些伪代码来查看是否可以帮助您。 manager-object可能看起来像这样:

class RequestManager {
    private let requiredNumberOfRequests: Int
    private let completionHandler: ()->()
    private var counter: Int {
        didSet {
            if counter == requiredNumberOfRequests {
                completionHandler()
            }
        }
    }

    init(numberOfRequests: Int, completionHandler: ()->()) {
        self.requiredNumberOfRequests = numberOfRequests
        self.completionHandler = completionHandler
        self.counter = 0
    }

    // Don't know exactly what you want to do here, but something like...
    func performRequest(success: (value: Double)->()) {
        // Network stuff, on success it looks like you'll have a Double(?)
        let value: Double = 234.09
        success(value: value)
        counter += 1
    }
}

然后,在循环之前,您将创建requestManager的实例

let manager = RequestManager(numberOfRequests: 100) { average in
    print("average: \(average)")
}

...并将performRequest作为循环的一部分调用。