是否有一种方法可以在其他应用程序中捕获一个应用程序中的错误

本文关键字:应用程序 错误 一个 一种 方法 是否 其他 | 更新日期: 2023-09-27 17:58:25

我正在处理两个不同的应用程序。

我正在应用程序1解决方案中调用应用程序2进程(.exe文件)。当应用程序2抛出"无效用户名和密码"错误时,我想在应用程序1解决方案中捕获该错误异常。

有没有一种方法可以在其他应用程序中捕获一个应用程序中的错误

我的应用程序是一个C#窗口应用程序

是否有一种方法可以在其他应用程序中捕获一个应用程序中的错误

有点。。。如果您实际上没有启动另一个进程,而是在现有进程中创建一个单独的AppDomain以在中运行可执行文件,则可以执行此操作。"内部"可执行文件还必须是CLR程序集。其他表示不可能进行跨进程异常处理的答案是正确的。这种方法只会解决问题,同时希望能给你想要的行为。

仅仅开始这个过程通常不会得到你想要的。

var process = Process.Start("MyInnerProcess.exe");

您将返回一个Process对象,该对象为您提供有关流程的各种有趣信息,并允许您监视写入标准输出流的内容。。。但无法真正访问进程中抛出的异常。

但是,如果您首先获取一个新的AppDomain以将程序集启动到中,则可以很容易地接收到该程序集在运行时引发的所有异常(包括未处理的异常和首次出现的异常!)的通知。(注意:对于这些例外情况,你无能为力……但你会知道它们正在发生。)

这是代码:

var innerDomain = AppDomain.CreateDomain("InnerDomain");
try
{
    //Subscribe to the events you are interested in     
    innerDomain.UnhandledException += innerDomain_UnhandledException;
    innerDomain.FirstChanceException += innerDomain_FirstChanceException;
    //Execute your assembly within the app domain
    innerDomain.ExecuteAssembly("MyInnerProcess.exe");
}
catch (Exception ex)
{
    //Handle exceptions when attempting to launch the process itself.
}
void innerDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    //Do something with the unhandled exceptions
}
void innerDomain_FirstChanceException(object sender, FirstChanceExceptionEventArgs e)
{
    //Do something with the first chance exceptions
}

现在,每当在另一个进程中抛出异常时,您都可以访问该异常。每个异常都会调用FirstChanceException处理程序(即使它在应用程序中处理得当),所以你可能不想订阅它。你可能对UnhandledException事件最感兴趣。还要记住,所有未处理的异常都将首先激发FirstChanceException(当它们被抛出时),然后如果它们在没有被处理的情况下一直冒泡,则激发UnhandledException。

您不能在进程边界之间抛出catch。您必须使用进程间通信技术。根据你的情况,有很多选择。

以下是一些选项的列表。。。

  1. 文件:进程A写入进程B正在侦听的日志文件。非常容易实现
  2. 命名管道或TCP/IP套接字:您可以使用一个或多个命名管道将两个进程链接在一起,并通过导线将数据从一个应用程序传输到另一个
  3. 消息队列:进程A可以侦听进程B将消息推送到的消息队列
  4. 数据库:进程A可以写入数据库,而进程B检查数据库。这可以是一个远程数据库,也可以是像SQLite数据库这样简单的数据库

使用文件或命名管道可能是解决问题的最简单方法。其他选项将取决于您的环境和要求。

添加到Jordan的解决方案中,您可以读取Application2的控制台输出流。

参考编号:http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput(v=vs.110).aspx

// Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();