如何处理外部不稳定的代码?

How to handle external not stable code?

我有 asp.net Web Api 2 正在使用外部 COM Object (pvxcom) 的应用程序。在 COM 对象挂起的某些原因中,我没有机会报告 pvxcom.

的错误

我需要想办法绕过这个问题。我想澄清几点。

  1. 如何设置外部源的最长执行时间?
  2. 如何强制浏览器重新发送请求? (这可能吗?)
  3. 如何找出 COM 对象挂在哪个过程中?
  4. 处理 com 对象并重新创建是好的做法吗?

你还有其他想法吗,怎么想出来的?

您可以 运行 它在一个线程中,如果它挂起或花费比预期更长的时间,您可以终止该线程。

这是我的 MVC 草图,但 WebApi 代码将是相同的。这是基于 this answer:

public ActionResult Index()
{
    var sw = new Stopwatch();
    Exception threadException = null;
    var workerThread = new Thread(() =>
    {
        try
        {
            sw.Start();

            // Access your COM here instead of sleep
            Thread.Sleep(6000);

            sw.Stop();
        }
        catch (Exception ex)
        {
            threadException = ex;
            sw.Stop();
        }
    });

    var timeoutTimer = new System.Threading.Timer((s) =>
    {
        workerThread.Abort();
    }, null, 5000, Timeout.Infinite);

    workerThread.Start();
    workerThread.Join();


    ViewBag.Message = String.Format("Time: {0}; Exception: {1}", sw.Elapsed, threadException);

    return View();
}