2012-09-03 138 views
10

VB6有一个DoEvents()方法,您可以调用该方法将控制权返回给操作系统,并在该单线程环境中模拟多线程行为。C#等价于VB 6 DoEvents

VB 6 DoEvents()的.NET框架相当于什么?

+1

我想你是在考虑Doevents。 Yield是枚举处理中使用的.NET方法。 .NET中的等价物是Application.DoEvents()(不管所用语言) – Zippit

+2

'Application.DoEvents()== DoEvents'? – Marlon

+0

@Marlon:我明白了。其实我记得每隔几年就会问这个问题。我不记得我最后一次提问的时间。你可能是对的,这可能是答案,但我的记忆使我失望。我也在想,我在System.Diagnostics.Process类的其中一个方法中找到了一个替代品,但我无法确定。 –

回答

8

Application.DoEvents()(的WinForms的一部分)

+0

WPF呢?我讨厌WinForms –

+3

@ColeJohnson旧的Application.DoEvents()方法已经在WPF中被删除,而倾向于使用[* Dispatcher *](http://msdn.microsoft.com/zh-cn/magazine/cc163328.aspx)或[* Background Worker Thread *](http://elegantcode.com/2009/07/03/wpf-multithreading-using-the-backgroundworker-and-reporting-the-progress-to-the-ui/)到按照您的描述进行处理。查看关于如何使用这两个对象的几篇文章的链接。 –

+0

通常,我不推荐使用DoEvents。它可以暂停GUI。 Google Application.DoEvents的问题 –

23

可以使用Application.DoEvents()。为什么不使用Threading class or simply Background Workers?如果您在.net环境中执行操作,请不要使用DoEvents。把它留在VB6上。

1

如果您在代码中调用Application.DoEvents(),您的应用程序可以处理其他事件。例如,如果您有一个表单将数据添加到ListBox并将DoEvents添加到您的代码中,那么您的表单会在另一个窗口被拖动时重绘。如果您从代码中删除DoEvents,则只有在按钮的单击事件处理程序完成执行后,您的表单才会重新绘制。有关消息传递的更多信息,请参阅Windows窗体中的用户输入。

与Visual Basic 6.0不同,DoEvents方法不调用Thread.Sleep方法。

5

以下是通用型的DoEvents方法

using System; 
using System.Windows.Threading; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Security.Permissions; 

namespace Utilites 
{ 
/// <summary> 
/// Emulates the VB6 DoEvents to refresh a window during long running events 
/// </summary> 
public class ScreenEvents 
{ 
    [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] 
    public static void DoEvents() 
    { 
     DispatcherFrame frame = new DispatcherFrame(); 
     Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, 
      new DispatcherOperationCallback(ExitFrame), frame); 
     Dispatcher.PushFrame(frame); 
    } 

    public static object ExitFrame(object f) 
    { 
     ((DispatcherFrame)f).Continue = false; 

     return null; 
    } 
} 
} 

它并不需要了解应用程序。