Although too late for OP, I'd like to register here the solution that worked for me.
I got the same error msg in the same position at InitializeComponent();
this.browse = new System.Windows.Forms.WebBrowser();
And same error msg after change control to:
this.axAcroPDF1 = new AxAcroPDFLib.AxAcroPDF();
I tried:
var thread = new Thread(async () =>
{
using var showDoc = new ShowDoc();
showDoc.ShowDocTask(_path, OriginalFileName, FileNameExtension);
});
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
thread.Join(); //Wait for the thread to end
And same error.
Finally, I saw How to force a task to run on an STA thread? [duplicate] that has a Stephen Cleary very interesting answer, and pointed me to the Set ApartmentState on a Task that solved this problem.
The Servy's and David's answers has the code for implement, respectively, a
public static Task<T> StartSTATask<T>(Func<T> func)
and a
public static Task StartSTATask(Action func)
both use new TaskCompletionSource<object>()
to carry back to the caller the Result or Exception that results from the Action or Func that is passed to a thread, that as VillageTech has pointed, has to be setted to thread.SetApartmentState(ApartmentState.STA)
. Only after all pieces in place they do a thread.Start();
and both return a (TaskCompletionSource) tcs.Task
i.e., the Result or Exception.
Very complex to think on my on, but after seeing, is as brilliant as is obvious.
PS:
I learned a lot in these links; after that, I returned to the MS pages and I finally I understood them a lot too:
How to: Wrap EAP Patterns in a Task and TPL and traditional .NET asynchronous programming,