2013-01-04 34 views
0

我在.NET 4上開發了一個簡單的Windows應用程序。 我想將參數傳遞給我的應用程序,如果此參數爲空,應用程序不應該繼續運行並退出。退出應用程序錯誤

我在main方法中添加了一個輸入參數。

「應用程序已停止工作」

我該怎麼處理這件事:當我調試它在我的Visual Studio中,但是當我執行我的應用程序的Windows直接給了我這個錯誤,它工作正常?我測試了一些代碼,但它不工作

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

這是5月主要方法:

[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 

回答

2

我上面沒有找到你的代碼的原因。

if this parameter was empty application do not continue running and exit works.

你可以很容易的代碼以這種方式

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

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

     Application.Run(new Form1()); 
    } 
} 
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只會做。雖然有一點細節。