我正在尝试从Web API(2.1)控制器运行STA(单线程单元)线程。
为此,我正在使用StaTaskScheduler:
/// <summary>Provides a scheduler that uses STA threads.</summary>
public sealed class StaTaskScheduler : TaskScheduler, IDisposable
{
/// <summary>Stores the queued tasks to be executed by our pool of STA threads.</summary>
private BlockingCollection<Task> _tasks;
/// <summary>The STA threads used by the scheduler.</summary>
private readonly List<Thread> _threads;
/// <summary>Initializes a new instance of the StaTaskScheduler class with the specified concurrency level.</summary>
/// <param name="numberOfThreads">The number of threads that should be created and used by this scheduler.</param>
public StaTaskScheduler(int numberOfThreads)
{
// Validate arguments
if (numberOfThreads < 1) throw new ArgumentOutOfRangeException("concurrencyLevel");
// Initialize the tasks collection
_tasks = new BlockingCollection<Task>();
// Create the threads to be used by this scheduler
_threads = Enumerable.Range(0, numberOfThreads).Select(i =>
{
var thread = new Thread(() =>
{
// Continually get the next task and try to execute it.
// This will continue until the scheduler is disposed and no more tasks remain.
foreach (var t in _tasks.GetConsumingEnumerable())
{
TryExecuteTask(t);
}
});
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
return thread;
}).ToList();
// Start all of the threads
_threads.ForEach(t => t.Start());
}
}
一种选择是从CustomHttpControllerDispatcher
运行STA线程:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
//constraints: null,
// - Trying to avoid this
//handler: new Controllers.CustomHttpControllerDispatcher(config)
);
}
public class CustomHttpControllerDispatcher : System.Web.Http.Dispatcher.HttpControllerDispatcher
{
public CustomHttpControllerDispatcher(HttpConfiguration configuration) : base(configuration)
{
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// My stuff here
}
}
但是,这需要手动构建http响应,其中涉及json序列化,我宁愿避免这种情况。
这使我有了当前选项,该选项正在控制器调用的库中运行STA线程(以生成自定义表单)。
如果使用带有Main
装饰的[STAThread]
的“ Windows应用程序”类型的测试应用程序调用该库,则一切正常。但是,从Web服务控制器调用时,以下任务返回时会出现“吞咽”异常:
注意:我不呈现任何对话框,因此不应存在任何“当应用程序不在UserInteractive模式下运行时显示模式对话框或表单不会有效的操作。” 例外,从CustomHttpControllerDispatcher
中启动的STA线程生成自定义表单时根本不会发生。
private Task<AClass> SendAsync1()
{
var staTaskScheduler = new StaTaskScheduler(1);
return Task.Factory.StartNew<CustomForm>(() =>
{
// - execution causes "swallowed exception"
return new AClass();
},
CancellationToken.None,
TaskCreationOptions.None,
staTaskScheduler
);
}
也就是说,当进行逐步调试时,堆栈跟踪将在经过之后消失:
return new AClass();
我通常通过缩小一些断点来解决这个问题,但是在这种情况下,我认为这是不可能的,因为没有Task.cs(以及大量相关文件)的调试符号或源。
注意:我现在可以逐步完成System.Threading.Tasks
的反汇编,但是调试过程可能会很漫长,因为它们不是无关紧要的库,因此,您将不胜感激。< / p>
我怀疑是b / c我正在尝试从MTA线程(控制器)调度STA线程,但不是肯定的吗?
用法
GetCustomForm().Wait();
private FixedDocumentSequence _sequence;
private async Task GetCustomForm()
{
// - will be slapped with a "calling thread cannot access...", next issue
_sequence = await SendAsync1b();
}
private readonly StaTaskScheduler _staTaskScheduler = new StaTaskScheduler(1);
private Task<FixedDocumentSequence> SendAsync1b()
{
//var staTaskScheduler = new StaTaskScheduler(100);
//var staTaskScheduler = new StaTaskScheduler(1);
return Task.Factory.StartNew<FixedDocumentSequence>(() =>
{
FixedDocumentSequence sequence;
CustomForm view = new CustomForm();
view.ViewModel = new ComplaintCustomFormViewModel(BuildingEntity.form_id, (int)Record);
sequence = view.ViewModel.XpsDocument.GetFixedDocumentSequence();
return sequence;
},
CancellationToken.None,
TaskCreationOptions.None,
_staTaskScheduler);
}
参考
- ASP.Net WebApi STA Mode
- Custom route handlers in ASP.Net WebAPI
- https://www.c-sharpcorner.com/article/global-and-per-route-message-handlers-in-webapi/
- https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers
- https://weblog.west-wind.com/posts/2012/Sep/18/Creating-STA-COM-compatible-ASPNET-Applications
答案 0 :(得分:0)
直接在STA线程中运行WPF /实体代码似乎可行:
Thread thread = GetCustomFormPreviewView4();
thread.Start();
thread.Join();
private Thread GetCustomFormPreviewView4()
{
var thread = new Thread(() =>
{
FixedDocumentSequence sequence;
CustomForm view = new CustomForm();
view.ViewModel = new ComplaintCustomFormViewModel(BuildingEntity.form_id, (int)Record);
sequence = view.ViewModel.XpsDocument.GetFixedDocumentSequence();
//view.ShowDialog();
//...
}
);
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
return thread;
}