在C#中合理使用线程? [英] A reasonable use of threading in C#?

查看:129
本文介绍了在C#中合理使用线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为大型自动化过程的一部分,我们正在调用第三方API,该API会做一些工作来调用另一台计算机上的服务.我们最近发现,当其他计算机不可用时,API调用有时会在尝试连接到远程服务器时最多旋转40分钟.

As part of a large automation process, we are calling a third-party API that does some work calling services on another machine. We discovered recently that every so often when the other machine is unavailable, the API call will spin away sometimes up to 40 minutes while attempting to connect to the remote server.

我们使用的API没有提供指定超时的方法,并且我们不希望程序等待那么长时间,因此我认为线程将是强制执行超时的好方法.生成的代码如下所示:

The API we're using doesn't offer a way to specify a timeout and we don't want our program waiting around for that long, so I thought threads would be a nice way to enforce the timeout. The resulting code looks something like:

 Thread _thread = new Thread(_caller.CallServices());

 _thread.Start();
 _thread.Join(timeout);

 if (_thread.IsAlive)
 {
      _thread.Abort();
      throw new Exception("Timed-out attempting to connect.");
 }

基本上,我想让APICall()运行,但是如果超时后仍然继续运行,请假定它将失败,将其杀死并继续前进.

Basically, I want to let APICall() run, but if it is still going after timeout has elapsed, assume it is going to fail, kill it and move on.

由于我是C#和.net运行时的新手,所以我想问两个相关的问题:

Since I'm new to threading in C# and on the .net runtime I thought I'd ask two related questions:

.net库中是否有一种更好/更合适的机制可以满足我的需要,我是否已在那段代码中提交了任何线程陷阱?

Is there a better/more appropriate mechanism in the .net libraries for what I'm trying to do, and have I committed any threading gotchas in that bit of code?

推荐答案

Thread.Abort()是线程中止的请求,但不能保证它会及时中止.这也被认为是不好的做法(它会在中止的线程中引发线程中止异常,但是似乎第三方API不能为您提供其他选择.

Thread.Abort() is a request for the thread to abort, and gives no guarantee that it will do so in a timely manner. It is also considered bad practice (it will throw a thread abort exception in the aborted thread, but it seems like the 3rd party API offers you no other choices.

如果您(通过编程方式)知道了远程服务主机的地址,则应先将其ping通,然后再将控制权转移给第三方API.

If you know (programmatically) the address of the remote service host you should ping it before you transfer control to the 3rd party API.

如果不使用后台工作程序,则可以将线程的IsBackgroundThread设置为true,这样就不会阻止程序终止.

If not using a backgroundworker, you could set the thread's IsBackgroundThread to true, so it doesn't keep your program from terminating.

这篇关于在C#中合理使用线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆