0

我在 .NET 4 上开发了一个简单的 Windows 应用程序。我想将一个参数传递给我的应用程序,如果此参数为空,则应用程序不应继续运行并退出。

我在 main 方法中添加了一个输入参数。当我在我的 Visual Studio 中调试它时它工作正常,但是当我直接执行我的应用程序时,Windows 给了我这个错误:

“应用程序已停止工作”

我该如何处理?我测试了一些代码,但它不起作用

 Application.ExitThread();
 Application.Exit();

这是可能的主要方法:

 [STAThread]
 static void Main(string[] args)
 {
     if(args.Count()==0)
      Thread.CurrentThread.Abort(); 

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Application.Run(new Form1());
 }

我查看了 Windows 事件查看器,发现了这个错误事件

Application: WindowsFormsApplication1.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Threading.ThreadAbortException
Stack:
at System.Threading.Thread.AbortInternal()
at System.Threading.Thread.Abort()
at WindowsFormsApplication1.Program.Main()

另一个:

Faulting application name: WindowsFormsApplication1.exe, version: 1.0.0.0, time 
stamp:    0x50e775e3
Faulting module name: KERNELBASE.dll, version: 6.1.7601.17514, time stamp: 0x4ce7c78c
Exception code: 0xe0434352
Fault offset: 0x000000000000a49d
Faulting process id: 0x15b4
Faulting application start time: 0x01cdeade1bdab018
Faulting application path: C:\WindowsFormsApplication1\WindowsFormsApplication1 
 \bin\Debug\WindowsFormsApplication1.exe
Faulting module path: C:\Windows\system32\KERNELBASE.dll
Report Id: 5a6d1a1f-56d1-11e2-8ffd-20cf30e7bd24
4

2 回答 2

4

我希望您提供的代码能做到这一点。调用会在线程 ( ,这将是未被捕获的)Thread.Abort()上引发异常。ThreadAbortException

如果您只想停止不带参数的处理,只需返回:

[STAThread]
 static void Main(string[] args)
 {
     if(args.Length ==0) return; // Will leave and end the application

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Application.Run(new Form1());
 }

你也可以Count()在数组上使用什么时候Length就可以了。不过小细节。

于 2013-01-04T12:54:07.453 回答
2

我不明白你上面的代码的原因。

如果此参数为空应用程序不要继续运行并退出工作。

你可以很容易地用这种方式编码

 [STAThread]
 static void Main(string[] args)
 {
     if(args.Length > 0)
     {

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Application.Run(new Form1());
     }
 }
于 2013-01-04T12:55:28.510 回答