简体   繁体   中英

C# blockingcollection in Swift

I am working on converting a C# application to Swift. Everything is going fine, but I am stuck at the point where the dev in the C# program used a Blocking collection:

public static BlockingCollection<MouseUsageMessage> mouseUsageMessageQueue = new BlockingCollection<MouseUsageMessage>();

Later on, they're adding something to the queue, just a simple integer passed to a class which returns a message that is added to the queue:

mouseUsageMessageQueue.Add(new MouseUsageMessage(0));

Then the program goes through the queue with a foreach using the ConsumingEnumerable of each message:

foreach(MouseUsageMessage msg in mouseUsageMessageQueue.GetConsumingEnumerable()){
     // do something
}

I don't have enough experience with Swift to know how I can do the same as described above in Swift. So my question here is: How can I do the same as what is done in C# (see code above) in Swift?

I'm not super experienced with C#, but I understand that BlockingCollection is just a thread safe array. In Swift arrays are not thread safe, however, you could wrap your arrays with a generic class and restrict access to it with a dispatch queue. I've seen they call this a synchronized collection on the internet, but the examples I've seen don't make use of the Collection protocol, losing a lot of functionality. Here is an example I wrote:

public class BlockingCollection<T>: Collection {

    private var array: [T] = []
    private let queue = DispatchQueue(label: "com.myapp.threading") // some arbitrary label

    public var startIndex: Int {
        return queue.sync {
            return array.startIndex
        }
    }

    public var endIndex: Int {
        return queue.sync {
            return array.endIndex
        }
    }

    public func append(newElement: T) {
        return queue.sync {
            array.append(newElement)
        }
    }

    public subscript(index: Int) -> T {
        set {
            queue.sync {
                array[index] = newValue
            }
        }
        get {
            return queue.sync {
                return array[index]
            }
        }
    }

    public func index(after i: Int) -> Int {
        return queue.sync {
            return array.index(after: i)
        }
    }
}

Thanks to the powerful protocols extensions in Swift, you get all the typical functions of a collection (forEach, filter, map, etc) for free.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM