Swift 中的 C# 阻塞集合

标签 c# swift blockingcollection

我正在致力于将 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/

相关文章:

c# - 如何使用c#在文本框中复制文本文件?

ios - 如何使用代码将 UISearchController Searchbar 放到导航栏上

ios - 通过来自 UITextField 的 Int 可选变量收到 "fatal error: unexpectedly found nil while unwrapping an Optional value"

ios - presentationNode 的位置正在重置

c# - 如何在 C# 中将按位非运算符与移位运算符一起使用?

c# - 从 SqlServer 通知应用程序

c# - 查找并调用通用重载方法

c# - 如何取消 BlockingCollection 上的 GetConsumingEnumerable()

c# - 多线程sqldatareader时间过期