Task.Run from UI thread throws STA error

后端 未结 2 1819
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 11:28

While I was refactoring some old C# code for document generation with Office.Interop library I found this and because of it was using UI context when function were

2条回答
  •  长发绾君心
    2021-01-21 12:05

    Because in this case Task presumably starts a new thread that isn't an STA thread. Your calls to updateDoc and newDoc are the ones that call the Interop layer, which doesn't like MTA threads.

    You could refactor this to use Thread instead of Task and set the apartment to STA by yourself. I would be careful though, because I am not sure Interop likes multi-threading.

提交回复
热议问题