用C#显式杀死线程

Bil*_*med 2 c# multithreading

我有C#代码,我在调用SAP BAPI,但有时需要很长时间才能获得响应.

我只能等待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);
Run Code Online (Sandbox Code Playgroud)

funcArtike2.Invoke(rfcDest); 是等待3秒后我想跳过的声明.

Tam*_*nut 5

试试这个:

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);
Run Code Online (Sandbox Code Playgroud)

我们假设电话:

funcArtike2.Invoke(rfcDest);
Run Code Online (Sandbox Code Playgroud)

是同步的,否则它将无法正常工作.

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