使用Rx实现IO操作Threadsafe

Implement IO operation Threadsafe using Rx

我正在尝试实现线程安全的文件 IO class。我知道这可以通过锁和信号量来实现。但我想使用 Rx,因为我正在学习使用 Rx。任何人都可以帮助我以线程安全的方式使用 Rx 实现以下 IO 操作合同。我有几个想法,比如创建用于保存或读取文件的外部请求管道,以有序的方式安排所有请求。但是我正在为如何实施而苦苦挣扎。请指导。

 public interface IFileIO
    {
        /// <summary>
        /// Task which writes text to the file asynchronously
        /// </summary>
        Task WriteTextAsync(IsolatedStorageFileStream storageFile, string text);

        /// <summary>
        /// Task which reads text from the file asynchronously
        /// </summary>
        Task<string> ReadTextAsync(IsolatedStorageFileStream storageFile);
    }

我不知道我是否错过了一些重要的东西,但你的界面应该是这样的:

public interface IFileIO
{
    IObservable<Unit> WriteTextAsync(IsolatedStorageFileStream storageFile, string text);
    IObservable<string> ReadTextAsync(IsolatedStorageFileStream storageFile);
}

然后您将使用 System.Reactive.Concurrency.EventLoopScheduler 来实现此实现以执行实现中的所有调度。这将确保所有操作都在单个线程上执行。真的超级简单。

接口中的Unit类型为System.Reactive.Unit,用作表示void的类型(或Task没有泛型)。您应该始终使用 System.Reactive.Unit.Default 来获取 Unit.

的相同实例