BilalAhmed BilalAhmed - 6 days ago 8
C# Question

Kill Thread Explicitly in C#

I have C# Code where I am invoking SAP BAPI, but sometime it takes too long to get a response back.

I can only wait for 3 seconds to get a response back. If it's does not return in 3 seconds, then I would like to terminate the call and continue with the next line.

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);
is the statement I want to skip after waiting for 3 seconds.

Answer

Try this:

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);

We assume that the call:

funcArtike2.Invoke(rfcDest);

is synchronous, otherwise it will not work.

Note also that this will not kill the funcArtike2.Invoke(rfcDest) method call, just ignore it and move on. So if you start any expensive operations (e.g. DB call, file, IO, heavy computation), bad luck since you need to take care of that yourself.

Comments