c# - 在 C# 中显式终止线程

标签 c# multithreading

我有调用 SAP BAPI 的 C# 代码,但有时需要很长时间才能得到响应。

我只能等待 3 秒才能得到回复。如果它在 3 秒内没有返回,那么我想终止通话并继续下一行。

funcArtike2.SetValue("CLI", CLI);             
funcArtike2.Invoke(rfcDest);

string CA = funcArtike2["CONTRACT_ACCOUNT"].GetValue().ToString().Trim() != "".ToString() ? funcArtike2["CONTRACT_ACCOUNT"].GetValue().ToString().Trim() : "X";
//IRfcStructure RETURN = funcArtike2["RETURN"].GetStructure();
string BP = funcArtike2["BUSINESS_PARTNER"].ToString().Substring(funcArtike2["BUSINESS_PARTNER"].ToString().IndexOf("=")+1);

funcArtike2.Invoke(rfcDest); 是等待 3 秒后我想跳过的语句。

最佳答案

试试这个:

AutoResetEvent signal = new AutoResetEvent(false);
Timer timer = new Timer(3000);
timer.Elapsed += (sender, e) => signal.Set();        

funcArtike2.SetValue("CLI", CLI);

Thread thread = new Thread(()=>{
            funcArtike2.Invoke(rfcDest);
            signal.Set();
        });

thread.Start(); //start the function thread
timer.Start(); //start the timer

signal.WaitOne(); //waits for either the timer to elapse or the task to complete

string CA = funcArtike2["CONTRACT_ACCOUNT"].GetValue().ToString().Trim() != "".ToString() ? funcArtike2["CONTRACT_ACCOUNT"].GetValue().ToString().Trim() : "X";
            //IRfcStructure RETURN = funcArtike2["RETURN"].GetStructure();
string BP = funcArtike2["BUSINESS_PARTNER"].ToString().Substring(funcArtike2["BUSINESS_PARTNER"].ToString().IndexOf("=")+1);

我们假设调用:

funcArtike2.Invoke(rfcDest);

是同步的,否则不行。

另请注意,这不会终止 funcArtike2.Invoke(rfcDest) 方法调用,只需忽略它并继续。因此,如果您开始任何昂贵的操作(例如,数据库调用、文件、IO、繁重的计算),运气不好,因为您需要自己处理。

关于c# - 在 C# 中显式终止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36221783/

相关文章:

c# - 用户控件 : How to add MouseWheel Listener?

c# - 在 SignalR 上发送/接收复杂对象

具有奇怪输出错误的 Python 线程

c - 多核和多 CPU 环境中的 mmap 线程安全

objective-c - 等待方法在 iOS 中完成

c# - 为什么我的图标没有出现在标题栏中?

c# - 如何使用相同的键向 StringValues 数组添加新值,从而修改我的 Uri?

c# - 在 C# 中使用 Web API 和 MS Graph SDK 访问 Microsoft Graph 时出现问题

wpf - WPF窗口实现ISynchronizeInvoke以与System.Timers.Timer一起使用

java - 如何显式释放 CountDownLatch