什么时候使用`IWebHost.Start()`方法有用呢?

And*_*man 8 c# asp.net-core-mvc asp.net-core-2.0

ASP.NET Core 2 MVC.

Microsift.AspNet.Hosting.IWebHostinterface 包含Start()方法.此外,Microsoft.AspNetCore.Hosting.WebHostExtensions该类定义Run()IWebHost接口的扩展方法.

Run()方法运行Web应用程序并阻止调用线程直到主机关闭.

同时该Start()方法在主机关闭之前不会阻塞调用线程.在这种情况下,浏览器在向用户显示信息之前关闭.

嗯......什么时候使用这个IWebHost.Start()方法有用呢?

Dav*_*idG 12

并非所有托管都是在经典的互联网服务页面中执行的.例如,您可能希望从WPF应用程序或Windows服务提供内容.在这种情况下,您可能不希望调用阻止 - 您的应用程序将有其他事情要做.例如,假设您有一个WPF应用程序并且您想要从中提供服务,您可以简单地扩展该main方法:

private IWebHost _webHost;

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    //Create the host
    _webHost = WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .Build();

    //We want to start, not run because we need the rest of the app to run
    _webHost.Start();

    //Run the app as normal
    Application.Run(new MainForm());

    //We're back from the app now, we can stop the host
    //...
}
Run Code Online (Sandbox Code Playgroud)