2011-12-30 6 views
0

여러 스레드 응용 프로그램에서 새 프로세스를 시작할 때 신중하게해야 할 문제가 있습니까?응용 프로그램 (C#)이 실행되는 동안 새 프로세스를 시작할 때 스레드가 중지되는 이유는 무엇입니까?

static void Main(string[] args) 
{ 
    Process.Start(@"D:\System\Desktop\a.txt"); 
    MessageBox.Show("Success"); 
} 

을 그리고 완벽하게 실행 :

나는 간단한 프로젝트에서 이것을 시도했다. 하지만 내 큰 프로젝트에서 여러 스레드를 사용하면 응용 프로그램 (다른 스레드)이 제대로 작동하는 동안 스레드가 작동하지 않습니다 ("a.txt"가 열리지 만 "성공"은 표시되지 않음).

이 경우 어떤 문제가 있습니까?

+0

Console.Writeline ("성공")을 시도해 볼 수 있습니까? 그 대신 작동하는지 확인하십시오. – neeKo

+0

나는 노력했다. 같은 결과! 이 프로세스를 시작하면 해당 스레드의 모든 내용이 중지됩니다! –

+0

흠, 이것을 재현 할 수 없습니다 ... 프로세스를 열고 콘솔에 메시지를 보내는 스레드를 만들었으므로 제대로 작동합니다 ... 다른 작업은 무엇입니까? 프로세스 전에 중단 점을 넣으십시오. 시작 및 다음 단계를 거쳐 실제로 중지되는지 (should shouldnt) – neeKo

답변

2

Windows.Forms 응용 프로그램이 있고 주 사용자 인터페이스 스레드가 아닌 스레드에서 메시지 상자를 표시하려고하면 메시지 상자의 동작이 정의되지 않습니다. 의미, 표시 될 수도 표시되지 않을 수도 있고, 일관성이 없거나 다른 문제 일 수도 있습니다.

예를 들어, BackgroundWorker의 DoWork 이벤트에서 메시지 상자를 표시하면 작동하지 않을 수도 있습니다. 어떤 경우에는 message-box-result가 어떤 버튼을 클릭했는지에 관계없이 항상 취소되었습니다.

따라서 디버깅 용으로 메시지 상자를 사용하는 경우 다른 기술을 사용하십시오. 메시지 상자를 표시해야하는 경우 기본 사용자 인터페이스 스레드에서 메시지 상자를 호출하십시오.

콘솔 응용 프로그램은 일반적으로 메시지 상자를 표시하는 데 문제가 없어야합니다. 그러나 메시지 박스 호출 전에 100ms 동안 스레드를 잠자 게해야하는 경우가있었습니다.

TomTom이 지적했듯이 주요 사용자 인터페이스 스레드는 응용 프로그램의 Windows 메시지 루프입니다. Windows 응용 프로그램에서 Windows 메시지에 응답 할 수 있도록 Windows 메시지 루프를 만들려면 콘솔 응용 프로그램에 양식을 만들어야했습니다.

+0

+1에 의해 해결되었으므로 누락 된 Windows 메시지 루프의 문제를 해결할 수 있습니다. – TomTom

+0

@TomTom; 그게 내가 기억할 수없는, 윈도우 메시지 루프. 감사. – AMissico

+0

내 문제는 메시지 상자를 표시하지 않습니다, 그냥 확인을위한 것입니다. 내 질문은 thread가 process.start (...) 호출 후 계속 작동하지 않는 이유입니다. –

0

Process.Start이 작동하는지 확인하십시오. 파일명을 전달하는 것은 어떤 경우에는 충분하지 않습니다. 샘플 코드에서 use-shell 속성을 설정해야합니다. 그렇지 않으면 cmd start <filename> 또는 동등 물을 사용해야합니다.

따라서 NotePad.exe를 시작하여 Process.Start이 작동하는지 확인하십시오. 문제가 해결되지 않으면 프로세스 명령과 명령 줄 문제입니다.

+0

동일한 문제 :'Process ptemp = new Process(); ptemp.StartInfo.FileName = "Notepad.exe"; ptemp.StartInfo.WindowStyle = ProcessWindowStyle.Maximized; ptemp.StartInfo.CreateNoWindow = false; ptemp.StartInfo.UseShellExecute = true; ptemp.Start(); "Success";'중단 점은'ptemp.Start();'에서 멈추고 성공 문자열을 반환하기 위해 계속 실행되지 않습니다. –

2

이 대답 아니다 - 나는 ... 코멘트에이 나를 ​​위해 작동

모든이 코드를 넣을 수 없습니다. 코드이 어떻게 다른지 말해 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Diagnostics; 
using System.Threading; 
using System.IO; 

namespace Test 
{ 
    class Program 
    { 
     const string OutputFile = @"E:\Output.txt"; 

     object _lock = new object(); 

     static void Main(string[] args) 
     { 
      Program program = new Program(); 

      Thread thread = new Thread(program.ThreadMethod); 
      thread.Start(@"E:\Test.txt"); 

      thread = new Thread(program.ThreadMethod); 
      thread.Start(@"E:\DoesntExist.txt"); 

      Console.ReadKey(); 
     } 

     void ThreadMethod(object filename) 
     { 
      String result = RunNormal(filename as string); 
      lock (_lock) 
      { 
       FileInfo fi = new FileInfo(OutputFile); 
       if (!fi.Exists) 
       { 
        try 
        { 
         fi.Create().Close(); 
        } 
        catch (System.Security.SecurityException secEx) 
        { 
         Console.WriteLine("An exception has occured: {0}", secEx.Message); 
         return; 
        } 
       } 

       StreamWriter sw = fi.AppendText(); 
       sw.WriteLine(result); 
       sw.Close(); 
      } 
     } 

     string RunNormal(string fullfilename) 
     { 
      try 
      { 
       Process.Start(fullfilename); 
       return fullfilename + "|Success"; 
      } 
      catch (Exception e) 
      { 
       return fullfilename + "|" + e.ToString(); 
      } 
     } 
    } 
} 

과 Output.txt의 출력은 다음과 같습니다

E:\DoesntExist.txt|System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified 
    at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo) 
    at System.Diagnostics.Process.Start() 
    at System.Diagnostics.Process.Start(ProcessStartInfo startInfo) 
    at System.Diagnostics.Process.Start(String fileName) 
    at Test.Program.RunNormal(String fullfilename) in E:\Projekti\VS2010\Test\Test\Program.cs:line 59 
E:\Test.txt|Success 

코드 얼마나 다른가요? 다른 방법을 부르니? 결과를 어떻게 처리합니까?

+0

+1; 좋은 코드. 나는 자물쇠, FileInfo, try ... catch 블록의 사용자를 좋아한다. – AMissico

+0

예, 새 프로젝트에서도 저 또한 효과가 있습니다. 하지만 제 큰 프로젝트에서는 그렇지 않습니다. 위의 내 기능과 동일합니다. –