[英]C# blockingcollection in Swift
我正在將C#應用程序轉換為Swift。 一切都很好,但是我陷入了C#程序中的開發人員使用Blocking集合的地步:
public static BlockingCollection<MouseUsageMessage> mouseUsageMessageQueue = new BlockingCollection<MouseUsageMessage>();
稍后,他們將一些東西添加到隊列中,只是將一個簡單的整數傳遞給類,該類將返回添加到隊列中的消息:
mouseUsageMessageQueue.Add(new MouseUsageMessage(0));
然后,程序使用每個消息的ConsumingEnumerable通過foreach遍歷隊列:
foreach(MouseUsageMessage msg in mouseUsageMessageQueue.GetConsumingEnumerable()){
// do something
}
我對Swift的經驗不足,無法知道如何做與Swift中上述相同的操作。 所以我在這里的問題是:我該如何做與Swift中C#(請參見上面的代碼)所做的相同?
我對C#並沒有超級的經驗,但是我知道BlockingCollection
只是一個線程安全的數組。 在Swift數組中,線程不是安全的,但是,您可以使用通用類包裝數組,並通過調度隊列限制對其的訪問。 我已經看到他們在Internet上將其稱為同步集合,但是我看到的示例並未利用Collection
協議,因此失去了很多功能。 這是我寫的一個示例:
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)
}
}
}
借助Swift中強大的協議擴展,您可以免費獲得集合的所有典型功能(forEach,filter,map等)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.