Is Application.DoEvents() just for WinForms?

大憨熊 提交于 2019-12-05 22:20:28

问题


Is Application.DoEvents() just for forms?

I thought that this command was used to ensure that all of the commands before are processed but now after reading the documentation, I'm not sure anymore.


回答1:


Yes, it's really aimed at Windows Forms. However, in my view it should be avoided where possible.

It's usually used as a hack by developers who don't want to be bothered with putting long-running operations on a different thread... but that means they're introducing re-entrancy issues which can be very hard to track down, as well as still blocking the UI thread for some of the time (and if that includes something like a file operation, you can't really predict whether the operation will complete quickly enough to not have a user visible effect).




回答2:


Without WinForms, there is no standard event queue. (Well, there is an event queue in WPF, but this is just another framework).




回答3:


If what you are trying to achieve is waiting for something to happen outside your application (eg. a file to be dropped in a certain directory), a possible workaround would be the Timer class of the System.Timers namespace.

An example (based on MSDN):

Private Sub SetTimer()
    Dim aTimer As New System.Timers.Timer
    AddHandler aTimer.Elapsed, AddressOf OnTimedEvent
    aTimer.Interval = 5000
    aTimer.Enabled = True

    Console.WriteLine("Press q to exit")
    While Console.Read <> Asc("q")
    End While
End Sub

Private Sub OnTimedEvent(ByVal source As Object, ByVal e As ElapsedEventArgs)
    'Do the job here
    Console.WriteLine("HELLO WORLD!")
    'Don't forget to disable the timer if you don't need it anymore
    'Source.Enabled = False
End Sub

More info at MSDN: http://msdn.microsoft.com/en-us/library/system.timers.timer%28v=vs.71%29.aspx




回答4:


Yes, it's only for Windows Forms. It wouldn't make sense in a console or ASP.NET application, because there is no message loop. It is possible to do it in WPF, using the dispatcher, as shown here. Anyway, I wouldn't recommend using DoEvents except perhaps in a quick and dirty application, for the reasons explained by Jon.



来源:https://stackoverflow.com/questions/4977702/is-application-doevents-just-for-winforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!