当我减少我的角色实例计数时,不会为死亡实例调用RoleEnvironment.Stopping/RoleEntryPoint.OnStop() 。它们在实例重新启动或部署停止时被调用。我做错了什么,还是在这种情况下我不应该需要清理?
我有一个简单的工作者角色(VS2012 更新 1,默认 Cloud 项目具有一个工作者角色,添加了smarx 的表存储跟踪侦听器)。所有代码在这里;没有其他依赖项:
using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
namespace WorkerRole1
{
public class WorkerRole : RoleEntryPoint
{
bool shouldRun = true;
EventWaitHandle runFinished = new EventWaitHandle(true, EventResetMode.ManualReset);
public override bool OnStart()
{
ServicePointManager.DefaultConnectionLimit = 12;
RoleEnvironment.Stopping += (object sender, RoleEnvironmentStoppingEventArgs e) => {
Trace.WriteLine("WorkerRole1 Stopping called", "Information");
shouldRun = false;
};
return base.OnStart();
}
public override void Run()
{
runFinished.Reset();
try {
Trace.WriteLine("WorkerRole1 entry point called", "Information");
while (shouldRun) {
Thread.Sleep(10000);
Trace.WriteLine("Working", "Information");
}
Trace.WriteLine("Finished", "Information");
} finally {
runFinished.Set();
}
}
public override void OnStop()
{
Trace.WriteLine("OnStop: Waiting for Run() to finish", "Information");
runFinished.WaitOne();
Trace.WriteLine("OnStop: Run() finished", "Information");
base.OnStop();
}
}
public class LogMessage : TableServiceEntity
{
public DateTime Time { get; set; }
public string Message { get; set; }
public string InstanceId { get; set; }
public string Category { get; set; }
public LogMessage() { }
public LogMessage(string message, string category)
{
Message = message;
Category = category;
Time = DateTime.UtcNow;
InstanceId = RoleEnvironment.CurrentRoleInstance.Id;
PartitionKey = RoleEnvironment.DeploymentId;
RowKey = (DateTime.MaxValue.Ticks - Time.Ticks).ToString("d19");
}
}
public class TableTraceListener : TraceListener
{
private TableServiceContext _context = null;
private TableServiceContext context
{
get
{
if (_context == null) {
var tables = CloudStorageAccount
.Parse(RoleEnvironment.GetConfigurationSettingValue(
Attributes["connectionStringName"] ?? "DataConnectionString"))
.CreateCloudTableClient();
tables.CreateTableIfNotExist("log");
_context = tables.GetDataServiceContext();
_context.MergeOption = MergeOption.NoTracking;
}
return _context;
}
}
protected override string[] GetSupportedAttributes() { return new[] { "connectionStringName" }; }
public override void Write(string message, string category)
{
context.AddObject("log", new LogMessage(message, category));
context.SaveChangesWithRetries();
}
public override void WriteLine(string message, string category) { Write(message + "\n", category); }
public override void Write(string message) { Write(message, null); }
public override void WriteLine(string message) { Write(message + "\n"); }
}
}