WebRole から WorkerRole のインスタンスを生成してみる

元ネタ:Windows Azure WorkerRoleの使い方のお作法?
WebRole 側の ASP.NET Web アプリから WorkerRole クラスのインスタンスを生成して、メソッドを呼び出すとの事です。
この発想は無かった!実際試してみましたが本番環境でも動作しました。


ですが、ログを見てみると WorkerRole 上で動いているのでは無く WebRole 上で動いています。WorkerRole クラスのインスタンスを自前で生成しているだけだからですかね?
ってことで、WorkerRole クラスのインスタンスを自前で生成してまで使う必要は無さそうです。WebRole、WorkerRole どちらからも使いたいコードがあるなら、別アセンブリに抜き出して両方から参照するのが良いのかな?
以下、コードの一部とログのイメージです。
※ログをストレージに出力する箇所は、Windows Azure ログ講座第一弾 〜Windows Azure logs〜 - waりとnaはてな日記 をそのままコピペしました。

Default.aspx

using System;
using WorkerRole1;

namespace WebRole1
{
  public partial class _Default : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btn_Click(object sender, EventArgs e)
    {
      WorkerRole role = new WorkerRole();
      role.hoge();
    }
  }
}

WorkerRole.cs

using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace WorkerRole1
{
  public class WorkerRole : RoleEntryPoint
  {
    public override void Run()
    {
      // This is a sample worker implementation. Replace with your logic.
      Trace.WriteLine("WorkerRole1 entry point called", "Information");

      while (true)
      {
        Thread.Sleep(10000);
        Trace.WriteLine("Working", "Information");
      }
    }

    public override bool OnStart()
    {
      // Set the maximum number of concurrent connections 
      ServicePointManager.DefaultConnectionLimit = 12;

      // ログ出力や診断情報を監視する構成を取得する
      var config = DiagnosticMonitor.GetDefaultInitialConfiguration();

      //Windows Azureトレース・ログを20秒単位で定期的に転送する
      config.Logs.ScheduledTransferPeriod = System.TimeSpan.FromSeconds(20);

      //Windows Azureトレース・ログを全て出力する
      config.Logs.ScheduledTransferLogLevelFilter = LogLevel.Undefined;

      //Windows Azure診断ログの出力開始
      DiagnosticMonitor.Start("DiagnosticsConnectionString", config);

      // For information on handling configuration changes
      // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
      RoleEnvironment.Changing += RoleEnvironmentChanging;

      return base.OnStart();

    }

    private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)
    {
      // If a configuration setting is changing
      if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))
      {
        // Set e.Cancel to true to restart this role instance
        e.Cancel = true;
      }
    }

    public void hoge()
    {
      Trace.WriteLine("HogeHoge!", "Information");
    }
  }
}