public static R CallWithTimeout<P, R>(Func<P, R> action, P p, out bool isTimeout, int millisecondsTimeout = Timeout.Infinite)
{
Thread threadToKill = null;
R r = default(R);
Action wrappedAction = () =>
{
threadToKill = Thread.CurrentThread;
r = action(p);
};
IAsyncResult result = wrappedAction.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(millisecondsTimeout))
{
wrappedAction.EndInvoke(result);
isTimeout = false;
}
else
{
//threadToKill.Abort();
//throw new TimeoutException();
Action abortAction = delegate
{
threadToKill.Abort();
};
abortAction.BeginInvoke(null, null);
isTimeout = true;
}
return r;
}
调用
public string FiveSecondMethod(int t)
{
// p = "1";
Thread.Sleep(t);
return "false" ;
}
private void button3_Click(object sender, EventArgs e)
{
int t1 = int.Parse(textBox1.Text);
bool btime=false;
// MyMethodB<string>(new Func<string, int>(MyMethodA), "feige");
// bool b = CallWithTimeout<int,bool>(new Func<int, bool>(FiveSecondMethod), t1,out btime, t1);
string s= CallWithTimeout(FiveSecondMethod, t1, out btime, t1);
}
在这里注意,返回值必须统一类型,R类型即为我们所有运行函数的类型。
下面这个是我自己改的,不知道是不是符合语法,或者是不是写的有问题,嗯,总之就这么用了,传两个参数。
static void CallWithTimeout2(Action<int ,string> action ,int CIO,string num, int timeoutMilliseconds)
{
Thread threadToKill = null;
Action wrappedAction = () =>
{
threadToKill = Thread.CurrentThread;
action(CIO, num);
};
IAsyncResult result = wrappedAction.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
wrappedAction.EndInvoke(result);
}
else
{
threadToKill.Abort();
// throw new TimeoutException();
return;
}
}
调用
private void button10_Click(object sender, EventArgs e)
{
CallWithTimeout2(WriteCar6, 30, "0040", 1000);
readCX = 5;
//Cx6 = 1;
// string Car6 = string.Empty;
// CIODZ = 30; //CIO30.06 车型6
// Car6 = getres1(("0040").ToString()).ToString();
//if (Car6 == "")
//{
// MessageBox.Show("写入不成功,请重新操作!");
//}
}
public void WriteCar6(int CIO ,string n)
{
string Car1 = string.Empty;
CIODZ = CIO; //CIO30.01 车型1
Car1 = getres1((n).ToString()).ToString();
}
这里应该是可以简写的,知道的帮我修改下,谢谢。getres1()是一个处理算法,太多不写了。
以上内容均为剽窃后修改。
原内容参考:https://www.cnblogs.com/CoreXin/p/12303622.html