gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:37:22 26 4
gpt4 key购买 nike

我有调用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com