我知道这是旧的,但达米安的回答和随后的评论帮助我解决了我的问题。我有一个控制台应用程序,我需要在其中调用async
在某些时候可能需要 STA 执行才能使用OpenFileDialog
.
这是我生成的代码,以防它帮助其他人(或只是我未来的自己)。
1.创建了以STA运行线程的扩展方法
public static class Extensions
{
public static void RunSTA(this Thread thread)
{
thread.SetApartmentState(ApartmentState.STA); // Configure for STA
thread.Start(); // Start running STA thread for action
thread.Join(); // Sync back to running thread
}
}
2.async main
使用await
应用程序方法创建方法(无[STAThread]
属性)。
class Program
{
static async Task Main(string[] args)
{
await App.Get().Run(args);
}
}
3. 使用扩展方法将OpenFileDialog
呼叫与 STA封装起来
public string[] GetFilesFromDialog(string filter, bool? restoreDirectory = true, bool? allowMultiSelect = true)
{
var results = new string[] { };
new Thread(() =>
{
using (var dialog = new OpenFileDialog())
{
dialog.Filter = filter;
dialog.RestoreDirectory = restoreDirectory ?? true;
dialog.Multiselect = allowMultiSelect ?? true;
if (dialog.ShowDialog() != DialogResult.OK)
return; // Nothing selected
results = dialog.FileNames;
}
}).RunSTA();
return results;
}