简体   繁体   English

Windows窗体中的异步

[英]Async in Windows Forms

Is it possible to do async stuff in WinForms like we can in Metro apps on Windows 8? 是否可以像在Windows 8上的Metro应用程序中那样在WinForms中执行异步内容?

For example: 例如:

protected async void Something()
{
    await FileIO.Something();
}

would be really cool to have in WinForms. 在WinForms中真的很酷。

Yes. 是。

Async is a C# 5.0 language feature and will work anywhere, as long as you have the supporting BCL types (.Net 4.5, or Microsoft.Bcl.Async from NuGet). Async是一种C#5.0语言功能,只要您拥有支持的BCL类型(.Net 4.5或NuGet的Microsoft.Bcl.Async),它就可以在任何地方使用。

However, you should never write async void s anywhere, except for event handlers. 但是,除了事件处理程序之外,您不应该在任何地方编写async void s。

Yes, you can obtain an asynchronous UI using async-await in winform. 是的,您可以在winform中使用async-await获取异步UI。 You have to start an asynchronous task in event handler with Tast.Run method without awaiting it. 您必须使用Tast.Run方法在事件处理程序中启动异步任务,而无需等待它。 To access any control property or method, you have to do it into main thread using Control.Invoke method. 要访问任何控件属性或方法,必须使用Control.Invoke方法将其转换为主线程。

At last, with this approach the ui remain ever active and can handle other event while previus code is running. 最后,通过这种方法,ui保持活跃状态​​,并且可以在正常代码运行时处理其他事件。 then you have to write code to disable enable button or other event handling while code is running 然后你必须编写代码来在代码运行时禁用启用按钮或其他事件处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM