简体   繁体   English

C#:在外部方法调用上等待特定时间以通知超时

[英]C#: Wait certain time on external method invocation to notify timeout

this is my question: 这是我的问题:

How could I handle a timeout on a method execution, the scenario is the following: 我如何处理方法执行超时,方案如下:

I have a C# .Net framework 4.0 Windows Service application. 我有一个C#.Net Framework 4.0 Windows Service应用程序。 I added a reference to a external COM assembly (of a specific software of certain company). 我添加了对(某些公司的特定软件的)外部COM程序集的引用。 With this assembly I intented to process some information against that third party software on my Windows Service, and repeat that task every X minutes (defined by user). 通过该程序集,我打算针对Windows Service上的第三方软件处理一些信息,并每隔X分钟(由用户定义)重复执行该任务。 This works well on a perfect scenario, the issue is when that third party software has some problems, that assembly just don't response and my Windows service get stuck on that execution with no answer, for example this is the code of that execution: 这在理想情况下效果很好,问题是当第三方软件出现问题,程序集不响应并且我的Windows服务卡在该执行中而没有答案时,例如,这是该执行的代码:

    var calObj = new CAL.Object(CalOperatins.SendNoSavingChanges);
//this SYNC execution method sometimes get stuck and 
//the rest of the program just doesn't executes
calObj.TerminateUserSession();

log.Log4Text(string.Format("Service cycle ended, waiting {0} for next execution.",paramTime));
}

As I mentioned on the comments of the code, the execution of TerminateUserSession is synchronous and if that software experiments some problem, my service get stucked in there and the Log4Text method (and everything below it) does not executes. 正如我在代码注释中提到的那样, TerminateUserSession的执行是同步的,并且如果该软件试验了一些问题,我的服务将卡在其中,并且Log4Text方法(及其下的所有内容)将不会执行。

Is there a way that I can handle a timeout for that TerminateUserSession method execution, keeping in mind that it's an external assembly and I can't change that code? 有没有一种方法可以处理那个TerminateUserSession方法执行的超时,同时要记住这是一个外部程序集,而我不能更改该代码? (yes, I can figure out that it's wrong programmed because of the lack of a timeout) (是的,我可以确定由于缺少超时而编程错误)

Thanks in advance. 提前致谢。

What about running that code on a thread for which you have a handle. 在具有句柄的线程上运行该代码呢? You can track the successful execution by toggling a boolean back and forth and kill the thread if it doesn't respond by the specified timeout. 您可以通过来回切换布尔值来跟踪成功执行,如果在指定的超时时间内没有响应,则杀死该线程。 After killing the thread you could relaunch it. 杀死线程后,您可以重新启动它。 However, this is not a perfect solution you might have to recreate your COM object when you kill the thread which always seems to take an excessive amount of time. 但是,这不是一个完美的解决方案,您在杀死线程时可能不得不重新创建COM对象,这似乎总是花费大量时间。

This would also be subject to what is happening in the COM object and if the TerminateUserSessions method can handle the effect. 如果TerminateUserSessions方法可以处理效果,则这也将取决于COM对象中发生的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM