【发布时间】:2016-05-03 21:56:29
【问题描述】:
我正在尝试使用 Akka.net 构建文件下载actor。它应该在下载完成时发送消息,同时报告下载进度。
在 .NET 中,有一些类支持使用多个事件的异步操作。例如WebClient.DownloadFileAsync 有两个事件:DownloadProgressChanged 和 DownloadFileCompleted。
最好使用基于任务的异步版本并使用.PipeTo 扩展方法。但是,我看不出这将如何与公开两个事件的异步方法一起工作。与WebClient.DownloadFileAsync 一样。即使使用WebClient.DownloadFileTaskAsync,您仍然需要使用事件处理程序来处理DownloadProgressChanged。
我发现使用它的唯一方法是在创建我的演员时连接两个事件处理程序。然后在处理程序中,我向 Self 和 Sender 发送消息。为此,我必须从事件处理程序内部引用参与者的一些私有字段。这对我来说感觉不对,但我看不到其他出路。
有没有更安全的方法在一个 Actor 中使用多个事件处理程序?
目前,我的解决方案如下所示(_client 是在 actor 的构造函数中创建的 WebClient 实例):
public void HandleStartDownload(StartDownload message)
{
_self = Self;
_downloadRequestor = Sender;
_uri = message.Uri;
_guid = message.Guid;
_tempPath = Path.GetTempFileName();
_client.DownloadFileAsync(_uri, _tempPath);
}
private void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
var completedMessage = new DownloadCompletedInternal(_guid, _tempPath);
_downloadRequestor.Tell(completedMessage);
_self.Tell(completedMessage);
}
private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
var progressedMessage = new DownloadProgressed(_guid, e.ProgressPercentage);
_downloadRequestor.Tell(progressedMessage);
_self.Tell(progressedMessage);
}
因此,当下载开始时,会设置一些字段。此外,我确保我 Become 处于隐藏更多 StartDownload 消息的状态,直到 Self 收到 DownloadCompleted 消息:
public void Ready()
{
Receive<StartDownload>(message => {
HandleStartDownload(message);
Become(Downloading);
});
}
public void Downloading()
{
Receive<StartDownload>(message => {
Stash.Stash();
});
Receive<DownloadCompleted>(message => {
Become(Ready);
Stash.UnstashAll();
});
}
作为参考,这是整个Actor,但我认为重要的东西直接在这篇文章中:https://gist.github.com/AaronLenoir/4ce5480ecea580d5d283c5d08e8e71b5
【问题讨论】: