0

I am attempting to write a printed form in F# using WPF controls—-and do so in an asynchronous workflow. Being new to this, I can’t figure out how to place the wpf controls, consumed by the F# asynchronous block, on a STA thread, without blocking the main thread.

I have a lot of printed forms and do not want to block the main thread.

How is a STA thread created for the F# asynchronous workflow?

Thanks in advance for any help.

Alan Wayne
  • 5,122
  • 10
  • 52
  • 95

1 Answers1

1

In pure WPF I don't think you have STA - that concept comes from the COM model. What you do have is a specific UI thread that must be used for communicating with the UI. To get that thread you can use SynchronizationContext.Current property when you are certain you are on the UI thread (e.g. in an event handler). Note: If SynchronizationContext.Current is null then you will be running in the thread pool rather than on the UI thread.

If you then pass that SynchronizationContext object into your async {} code, you should be able to rejoin the UI thread by calling Async.SwitchToContext

tranquillity
  • 1,619
  • 1
  • 5
  • 12
  • @tranquility So...how do I create a thread that is not on the UI so wpf controls can be built for printing??? – Alan Wayne Sep 29 '22 at 02:59
  • @AlanWayne Within an `async` block you can use `do! Async.SwitchToThreadPool` to switch to a random background thread. – tranquillity Sep 29 '22 at 04:32
  • The threads in the thread pool are MTA, how do I change that to STA as needed by the controls? Thanks. – Alan Wayne Sep 30 '22 at 03:23
  • @AlanWayne Have you tried `Thread.CurrentThread.TrySetApartmentState(ApartmentState.STA)` it is documented as throwing `PlatformNotSupportedException` but it returns true for me (.Net 6). – tranquillity Oct 04 '22 at 04:45