我正在致力于将 C# 应用程序转换为 Swift。一切都很顺利,但我被困在 C# 程序中的开发人员使用阻塞集合的地方:
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 中,数组不是线程安全的,您可以使用泛型类包装数组,并使用调度队列限制对其的访问。我在互联网上看到他们称之为同步集合,但我看到的示例没有使用 Collection
协议(protocol),丢失了很多功能。这是我写的一个例子:
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 中强大的协议(protocol)扩展,您可以免费获得集合的所有典型功能(forEach、filter、map 等)。
关于Swift 中的 C# 阻塞集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50832820/