gpt4 book ai didi

c# - 如何在 async-Main 的入口线程上恢复?

转载 作者:行者123 更新时间:2023-11-30 13:06:46 25 4
gpt4 key购买 nike

我正在使用 C# 7.3 和 async Task Main() WPF 应用程序中的入口点。我正在实现自己的 Main方法,这样我就可以安全地运行一些 async进入 WPF 生成的 Application.Main 之前的方法方法(因为在 async 中使用 OnStartup 代码不适用于我的情况)。

问题是 WPF 需要主入口线程(我注意到是 STA 线程)作为调用 Application.Run 的线程。 (通过 Application.Main )。但我不知道如何获得await在入口线程上恢复。我假设是因为我没有指定 .ConfigureAwait(false)它将被迫在同一个线程上恢复,但现在我知道这只是非默认情况下的情况 SynchronizationContext已建立,就像在 WPF 和 WinForms 中一样,它在我的代码中尚不存在( System.Threading.SynchronizationContext.Current 返回 null )。

这是我的代码:

public static class Program
{
[STAThread]
public static async Task Main(String[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

await XmlDocumentConfigurationService.Instance.LoadConfigAsync();

RegisterDependencies( SimpleIoc.Default );

MyApplication.Main(); // fails because now the thread is not the entry thread
}
}

MyApplication.xaml.cs/MyApplication.g.i.cs(WPF 生成):

/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public static void Main() {
MyApplication app = new MyApplication();
app.InitializeComponent();
app.Run();
}

我知道我可以使用 Stephen Cleary 的 AsyncEx图书馆的AsyncContext类来同步运行我的异步代码,但这违背了使用 async Main 的意义- 并添加另一组依赖项:

[STAThread]
public static void Main()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

AsyncContext.Run( XmlDocumentConfigurationService.Instance.LoadConfigAsync );

RegisterDependencies( SimpleIoc.Default );

MyApplication.Main();
}

更新:尝试使用 DispatcherSynchronizationContext :

由于这是一个 WPF 应用程序,我想我会尝试使用 System.Windows.Threading.DispatcherSynchronizationContext :

Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
DispatcherSynchronizationContext context = new DispatcherSynchronizationContext( dispatcher );
SynchronizationContext.SetSynchronizationContext( context );

await XmlDocumentConfigurationService.Instance.LoadConfigAsync();

// (execution never gets here)
RegisterDependencies( SimpleIoc.Default );

MyApplication.Main();

...不幸的是执行到了await声明,但之后永远不会继续。我假设这是因为我没有将 Dispatcher 连接到 Win32 消息循环 - 我不确定我是否想自己做,因为 WPF 会在 app.Run(); 中自行完成它.

最佳答案

默认情况下,Visual Studio (2017) 中的新项目仅适用于该语言的最新主要版本(即 7.0),但您可以更改它。请关注Ben Willi的博客

关于c# - 如何在 async-Main 的入口线程上恢复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50901586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com