开发学院软件开发C语言 适合C# Actor的消息执行方式(6):协变与逆变 阅读

适合C# Actor的消息执行方式(6):协变与逆变

 2010-09-30 20:50:09 来源:WEB开发网   
核心提示: publicclassParent{publicvoidParentMethod(){};}publicclassChild:Parent{}staticvoidMain(string[]args){IPort<Child>childPort=newChildPortType();I

public class Parent 
{ 
  public void ParentMethod() { }; 
} 
 
public class Child : Parent { } 
 
static void Main(string[] args) 
{ 
  IPort<Child> childPort = new ChildPortType(); 
  IPort<Parent> parentPort = childPort; // 自动转化 
  parentPort.Post(p => p.ParentMethod()); // 可以接受Action<Parent>类型作为消息 
}

这意味着,我们可以把ICrawlRequestHandler和ICrawlResponseHandler类型写成下面的形式:

internal interface ICrawlRequestHandler 
{ 
  void Crawl(IPort<ICrawlResponseHandler> collector, string url); 
} 
 
internal interface ICrawlResponseHandler 
{ 
  void Succeeded(IPort<ICrawlRequestHandler> crawler, string url, string content, List<string> links); 
  void Failed(IPort<ICrawlRequestHandler> crawler, string url, Exception ex); 
} 

如今,Monitor和Crawler便可以写成如下模样:

internal class Crawler : Actor<Action<Crawler>>, IPort<Crawler>, ICrawlRequestHandler 
{ 
  protected override void Receive(Action<Crawler> message) { message(this); } 
 
  #region ICrawlRequestHandler Members 
 
  void ICrawlRequestHandler.Crawl(IPort<ICrawlResponseHandler> collector, string url) 
  { 
    try 
    { 
      string content = new WebClient().DownloadString(url); 
 
      var matches = Regex.Matches(content, @"href=""(http://[^""]+)""").Cast<Match>(); 
      var links = matches.Select(m => m.Groups[1].Value).Distinct().ToList(); 
      collector.Post(m => m.Succeeded(this, url, content, links)); 
    } 
    catch (Exception ex) 
    { 
      collector.Post(m => m.Failed(this, url, ex)); 
    } 
  } 
 
  #endregion 
} 
 
public class Monitor : Actor<Action<Monitor>>, IPort<Monitor>, ICrawlResponseHandler 
{ 
  protected override void Receive(Action<Monitor> message) { message(this); } 
 
  #region ICrawlResponseHandler Members 
  void ICrawlResponseHandler.Succeeded(...) { ... } 
  void ICrawlResponseHandler.Failed(...) { ... } 
  #endregion 
 
  private void DispatchCrawlingTasks(IPort<ICrawlRequestHandler> reusableCrawler) 
  { 
    if (this.m_readyToCrawl.Count <= 0) 
    { 
      this.WorkingCrawlerCount--; 
    } 
 
    var url = this.m_readyToCrawl.Dequeue(); 
    reusableCrawler.Post(c => c.Crawl(this, url)); 
 
    while (this.m_readyToCrawl.Count > 0 && 
      this.WorkingCrawlerCount < this.MaxCrawlerCount) 
    { 
      var newUrl = this.m_readyToCrawl.Dequeue(); 
      IPort<ICrawlRequestHandler> crawler = new Crawler(); 
      crawler.Post(c => c.Crawl(this, newUrl)); 
 
      this.WorkingCrawlerCount++; 
    } 
  } 
}

上一页  1 2 3 4 5 6 7  下一页

Tags:适合 Actor 消息

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接