【问题标题】:.Net Core web application running STA thread.Net Core Web 应用程序运行 STA 线程
【发布时间】:2020-11-24 19:16:04
【问题描述】:

我想在控制器中以 STA 模式运行 GET 方法。 对于 Web API,这非常有效: http://ryanhaugh.com/archive/2014/05/24/supporting-sta-threads-in-web-api/ 可以翻译成.NET Core吗?

【问题讨论】:

  • 试试看。请记住,代码在() => base.InvokeActionAsync(context, cancellationToken).Result 中的.Result 并不能真正发挥async 的作用。这将使其至少在某些方面同步
  • 你为什么还要这个?我找不到更好的方法来破坏性能
  • 我有一个用 COM 编写的旧应用程序,我希望允许用户通过 GET / POST 请求使用它。
  • 创建一个 Windows 服务,使用 WCF 或 SignalR 与 ASP.NET Core 应用程序通信并完成。不要不必要地杀死服务器
  • @MickyD 是的,当然,这些只是样本。无论如何,您都可以将 WCF 与命名管道一起使用

标签: c# asp.net-core-2.0 sta


【解决方案1】:

我现在用同样的方式做,只是我创建线程的方式不同。

Example example = new Example();
Thread thread =  = new Thread(
        delegate () //Use a delegate here instead of a new ThreadStart
        {
              example.StaRequired(); //Whatever you want to call with STA
        }
)
{
    IsBackground = false,
    Priority = ThreadPriority.Normal
};
thread.SetApartmentState(ApartmentState.STA);
thread.Start(); //Start the thread
thread.Join(); //Block the calling thread

IsBackgroundPriority 部分当然是可选的。

希望这对某人有所帮助

【讨论】:

    【解决方案2】:

    为了使用 STA,我创建了新线程:

    ComClass c = new ComClass();
    Thread t = new Thread(new ThreadStart(() => 
    {
        c.StaRequired();
    }));
    t.SetApartmentState(ApartmentState.STA);
    t.Start();
    t.Join();
    

    【讨论】:

    • Web 应用程序通常不应该参与构建 Web 服务器不知道的显式线程的业务。
    • 我将线程开始移动到 ComClass 作为一个新方法。这有意义吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 2019-10-04
    相关资源
    最近更新 更多