Chr*_*ris 2 .net c# topshelf async-await
我们像这样使用 TopShelf 来启动我们的服务。不过,我们在服务启动和停止方面看到了一些奇怪的问题,并想知道这是否是由于我们的异步启动/停止方法造成的。从未提及使用 async 查看文档。在他们的 github 页面上有一个提到你不应该以这种方式使用异步。
但是,话虽如此,它编译和运行(大部分)没问题。那么这是正确的还是我应该使用 a.Wait()来代替?
var host = HostFactory.New(hostConfig =>
{
hostConfig.Service<StreamClient>(serviceConfig =>
{
serviceConfig.ConstructUsing(name => new StreamClient());
serviceConfig.WhenStarted(async tc => await tc.Start());
serviceConfig.WhenStopped(async tc => await tc.Stop());
});
hostConfig.RunAsLocalSystem();
hostConfig.SetDescription("Stream Client Service");
hostConfig.SetDisplayName("Stream Client Service");
hostConfig.SetServiceName("StreamClientService");
});
host.Run();
Run Code Online (Sandbox Code Playgroud)
@Nkosi 询问方法签名是什么样的,它们是异步的并且启动内部客户端和进程。
public async Task Start()
{
// Dont start again if we are already running, or if we are already in the starting state
if (this.Running || this.Starting)
{
return;
}
await this.slackService.SendSlackServiceEvent(ServiceEventType.Starting, serviceName, applicationVersion);
this.Starting = true;
this.Stopping = false;
var configurationBuilder = new ClientConfigurationBuilder();
ClientConfiguration clientConfiguration;
if (Constants.UseLocalConnection)
{
await this.OnClientDebugMessage($"Using Local Connection");
clientConfiguration = configurationBuilder.CreateLocalConfiguration();
}
else
{
await this.OnClientDebugMessage($"Using SQL Connection");
clientConfiguration = configurationBuilder.CreateSqlConfiguration();
}
this.ClusterGrainClient = await this.StartClient(clientConfiguration);
if (this.ClusterGrainClient == null)
{
using (ConsoleColours.TextColour(ConsoleColor.Red))
{
await this.OnClientDebugMessage($"Cluster client null, aborting!");
}
return;
}
this.Running = true;
await this.OnClientStarted();
await this.slackService.SendSlackServiceEvent(ServiceEventType.Started, serviceName, applicationVersion);
this.Starting = false;
}
Run Code Online (Sandbox Code Playgroud)
无论是否为 Topshelf,Windows Service 主机都会启动该服务,而不是运行它。
我自己从来没有尝试过,但你可以尝试这样的事情:
public void Start() => this.StartAsync().GetAwaiter().GetResult();
public void Stop() => this.Stop().GetAwaiter().GetResult();
public async Task StartAsync()
{
// ...
}
public async Task StopAsync()
{
// ...
}
Run Code Online (Sandbox Code Playgroud)