winforms 如何从非UI线程创建窗体

1tu0hz3e  于 2023-10-23  发布在  其他
关注(0)|答案(1)|浏览(158)

我使用类似的代码,但这是行不通的,因为客户端subscibe回调操作是在非UI线程运行。如何将回调操作计划到Windows窗体UI线程?

  1. internal static class Program
  2. {
  3. [STAThread]
  4. private static void Main()
  5. {
  6. Application.SetHighDpiMode(HighDpiMode.SystemAware);
  7. Application.EnableVisualStyles();
  8. Application.SetCompatibleTextRenderingDefault(false);
  9. using (var context = new ProgramApplicationContext())
  10. {
  11. Application.Run(context);
  12. }
  13. }
  14. }
  15. internal class ProgramApplicationContext : ApplicationContext
  16. {
  17. public ProgramApplicationContext()
  18. {
  19. ...
  20. _client.subscribe("event", message => {
  21. var form = new CommunicationForm();
  22. form.Show();
  23. });
  24. }
  25. }
gopyfrb3

gopyfrb31#

您可以使用SynchronizationContext在UI线程上创建表单。

  1. public ProgramApplicationContext()
  2. {
  3. ...
  4. var ctx = SynchronizationContext.Current;
  5. _client.subscribe("event", message => {
  6. ctx.Send(state => {
  7. var form = new CommunicationForm();
  8. form.Show();
  9. }, null);
  10. });
  11. }

相关问题