c# - 程序运行时 C# 程序的初始形式不可用

标签 c#

我在让我的程序中的主窗体按我想要的方式运行时遇到问题。我正在使用 C#。在我的初始主窗体 (Form1) 上,我有一个运行长程序的命令按钮。在程序的中间,我希望用户能够返回到初始表单并单击我将在 C# 程序中放置在该初始表单上的一些新复选框。下面的代码只是卡住初始表单。我不需要让下面的代码正常工作。我只需要它来允许我访问我使用命令按钮启动的程序中间的主要初始表单。

为此,我有一个调用计时器的无限 while 循环。这是正确的方法吗?我不需要下面的程序来工作。我只需要能够在程序中间访问该初始表单。由于它不起作用,因此似乎不是这样做的方法,但正确的方法是什么?

以下代码运行下面的 OnTimedEvent 函数(方法)。该函数用于放置消息框,但我将其注释掉了。我不需要那个功能来工作。它仅用于测试目的。我的目标是我需要初始主窗体以允许我在从命令按钮运行时输入更多信息。下面的函数运行了大约 15 次,我得到了错误

Exception of type 'System.OutOfMemoryException' was thrown.

在线 aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

代码如下:

System.Timers.Timer aTimer;
// Create a timer with a one second interval.
aTimer = new System.Timers.Timer(100);

while (true)
{
    // Hook up the event handler for the Elapsed event.
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

    // Only raise the event the first time Interval elapses.
    aTimer.AutoReset = false;
    aTimer.Enabled = true;  // uncommented this now
    //addded  below
    aTimer.Start();
}

我尝试了几种不同的方法,但主窗体总是卡住。我只想能够在主窗体 (Form1) 上选择内容(例如复选框),因此可能不需要下面的代码。上面的计时器调用下面的 OnTimedEvent

private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
  // MessageBox.Show("Hello World");
}

在网络上的许多地方(包括 stackoverflow)我都看到我应该使用计时器来使主要的初始表单可用,但上面的代码只会导致表单被卡住并且我得到了顶部的栏表示它没有响应的形式。 我使用的是 Windows XP 和 Visual Studio 2008。如上所述,我使用的是 C#。

总而言之,上面的代码是否是在命令按钮运行后获取主要初始表单可用的正确方法?如果是,我做错了什么?如果这不是正确的方法,那是什么?

顺便说一句,我问了一个关于这个项目完全不相关的问题here

有什么想法吗?

最佳答案

你应该简单地删除 while 循环

    System.Timers.Timer aTimer;
    // Create a timer with a one second interval.
    aTimer = new System.Timers.Timer(1000);
    // Hook up the event handler for the Elapsed event.
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

    // Only raise the event the first time Interval elapses.
    aTimer.AutoReset = false;
    aTimer.Enabled = true;  // uncommented this now
    //addded  below
    aTimer.Start();

当您启动定时器时,它在一个单独的线程上运行。您的 while 循环只会不断地启动计时器。

System.Timers.Timer

关于c# - 程序运行时 C# 程序的初始形式不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16199968/

相关文章:

c# - SslStream 设置密码套件

c# - Windows RT 和 C#

c# - 从 c char* 到 string/IntPtr c# 的转换

c# - 用于查找用户是否启用了 MFA 的 Azure AD Batch 服务 API

c# - Windows 事件日志中的这个条目是什么意思?

C# Azure Blob 存储在慢速 Internet 连接上上传失败

c# - ("") 和 (null) 有什么区别

c# - DataGridView 只读 "bug"

c# - 什么是 .NET 托管模块?

c# - 可为空的 int 特定于 String() 的文化