C# 中事件和更改令牌之间的区别
Difference between events and change tokens in C#
我正在开发一个从文件加载一些数据的 C# 应用程序。每当文件发生更改时,应用程序都需要加载数据并执行一些操作。使用 FileSystemWatcher
class 可以直接观看文件。使用 event
通知应用程序的其余部分也很直接。然而,在研究解决方案时,我发现 IOptionsMonitor
接口,它使用 OnChange
函数而不是事件:
public IDisposable OnChange (Action<out TOptions, string> listener);
根据source.dot.net, the default implementation OptionsMonitor
watches some change tokens, connects them to an internal _onChange
event, which then invokes the listeners. Doing further research, I stumbled over the IFileProvider
接口,其中包含一个Watch
方法,即returns更改令牌:
public IChangeToken Watch (string filter);
我读了IChangeToken
documentation and the Detect changes with change tokens in ASP.NET Core article。但是,我没有看到更改令牌优于事件的优势。在我看来,更改令牌和事件都提供相同的功能 - 通知某些听众发生了某些事情 - 而事件更容易实现并且众所周知。当我只能使用事件代替时,为什么我会想要使用更改令牌?我是否遗漏了更改令牌的一个重要功能?
IChangeToken
是另一层,允许在不依赖它的情况下监听一些其他对象事件。
因此,当 B 想要使用事件监听 A 的变化时 - B 必须知道(依赖于)A。但是对于 IChangeToken
,A 和 B 都依赖于 IChangeToken
,但它们确实如此根本不需要互相了解
我正在开发一个从文件加载一些数据的 C# 应用程序。每当文件发生更改时,应用程序都需要加载数据并执行一些操作。使用 FileSystemWatcher
class 可以直接观看文件。使用 event
通知应用程序的其余部分也很直接。然而,在研究解决方案时,我发现 IOptionsMonitor
接口,它使用 OnChange
函数而不是事件:
public IDisposable OnChange (Action<out TOptions, string> listener);
根据source.dot.net, the default implementation OptionsMonitor
watches some change tokens, connects them to an internal _onChange
event, which then invokes the listeners. Doing further research, I stumbled over the IFileProvider
接口,其中包含一个Watch
方法,即returns更改令牌:
public IChangeToken Watch (string filter);
我读了IChangeToken
documentation and the Detect changes with change tokens in ASP.NET Core article。但是,我没有看到更改令牌优于事件的优势。在我看来,更改令牌和事件都提供相同的功能 - 通知某些听众发生了某些事情 - 而事件更容易实现并且众所周知。当我只能使用事件代替时,为什么我会想要使用更改令牌?我是否遗漏了更改令牌的一个重要功能?
IChangeToken
是另一层,允许在不依赖它的情况下监听一些其他对象事件。
因此,当 B 想要使用事件监听 A 的变化时 - B 必须知道(依赖于)A。但是对于 IChangeToken
,A 和 B 都依赖于 IChangeToken
,但它们确实如此根本不需要互相了解