0

我有一个用 C# 编写的应用程序。基本上它是一个exe。此应用程序每隔 3 秒扫描一次网络,并使用网络信息填充数据库。

我想从 asp.net mvc 运行这个应用程序几秒钟,然后停止它,然后再次启动和停止。

我需要在单击开始按钮时启动 exe,并且需要在单击停止按钮时停止它。该 exe 将持续运行,直到我在它被调用后单击停止按钮。

是否可以从 asp.net mvc 框架调用这个 exe?

如果是,怎么做?我需要一些指示。请提供给我。

4

1 回答 1

0

您将需要命名空间 System.Diagnostics 和 System.Timers。然后按照以下步骤操作。

    static System.Timers.Timer tTimer;
    const Int32 iInterval = 30;
    static Boolean IsProcessRunning = false;
    static Int32 iProcessID = 0;

    static Int32 SetTimerInterval(Int32 minute)
    {
        if (minute <= 0)
            minute = 60;
        DateTime now = DateTime.Now;

        DateTime next = now.AddMinutes((minute - (now.Minute % minute))).AddSeconds(now.Second * -1).AddMilliseconds(now.Millisecond * -1);

        TimeSpan interval = next - now;

        return (Int32)interval.TotalMilliseconds;
    }

    static void timer_Elapsed(object sender, EventArgs e)
    {   
        if (!IsProcessRunning)
        {   
            ProcessStartInfo objStartInfo = new ProcessStartInfo();
            objStartInfo.FileName = "C:\\Windows\\notepad.exe";

            Process objProcess = new Process();
            objProcess.StartInfo = objStartInfo;
            objProcess.Start();

            iProcessID = objProcess.Id;
            IsProcessRunning = true;
        }
        else
        {
            Process objProcess = Process.GetProcessById(iProcessID);
            objProcess.Kill();
            IsProcessRunning = false;
        }

        tTimer.Interval = SetTimerInterval(iInterval);
    }

然后在您的开始按钮上单击...

    tTimer = new System.Timers.Timer();
    tTimer.Interval = SetTimerInterval(iInterval);
    tTimer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    tTimer.Start();

您可以随时通过...停止此操作

    tTimer.Stop();

你准备好了……

于 2012-11-20T05:12:18.900 回答