我有 asp.net
Web Api 2
应用程序正在使用外部 COM 对象 (pvxcom)
。在 COM 对象挂起的某些原因中,我没有机会报告 pvxcom
的错误。
我需要想办法绕过这个问题。我想澄清几点。
- 如何设置外部源的最长执行时间?
- 如何强制浏览器重新发送请求? (这可能吗?)
- 如何确定 COM 对象卡在了哪个过程中?
- 处理 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();
}
关于c# - 如何处理外部不稳定的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32450160/