gpt4 book ai didi

c# - 我可以编写一个通用方法来调用超时的其他方法吗?

转载 作者:行者123 更新时间:2023-11-30 21:23:55 25 4
gpt4 key购买 nike

我遇到了一个很多人都熟悉的问题:我正在调用(具体来说是 Forest.GetCurrentForest()),在某些情况下,该调用将无法工作并引发异常。问题不大,抓到妥善处理就好了。但是,调用失败时非常慢;完全完成需要 30 秒。

我一直在寻找调用该方法的方法,但设置了超时,以便我们可以在更短的时间后停止。我发现了一个有趣的建议 here但如果我能解决的话,我想要一个更通用的解决方案。该解决方案在获得超时的额外费用上也相当繁重。我希望它会像说一样简单

CallMethodWithTimeout(Delegate method, int timeout)

但我不确定这样的事情是否会奏效。关于做类似事情的任何建议,或者在 C# 中是不可能的?我们也坚持使用 .NET 2.0。

除此之外,我将对避免 GetCurrentForest() 调用花费 30 秒来确定它没有发生发表评论。虽然我想知道那个通用方法调用方法的可行性。

最佳答案

我想了想并提出了以下方法(它本质上是迈克尔在我编写代码时所写内容的实现):

private static bool TimedMethodCaller(Delegate dlgt, int timeout, 
params object[] args)
{
ManualResetEvent waitHandle = new ManualResetEvent(false);
Thread t = new Thread(new ThreadStart(delegate
{
dlgt.Method.Invoke(dlgt.Target, args);
waitHandle.Set();
}));
t.Start();
return waitHandle.WaitOne(timeout);
}

使用此方法,您可以发布任何您喜欢的委托(delegate)和参数。它确实有不处理返回值的缺点(但这也可以通过某种方式实现)。

你可以这样调用它:

// parameter-less method call
bool success = TimedMethodCaller(new Action(ParamlessTestMethod), 100);

如果你想调用一个带参数的方法,你需要一个合适的委托(delegate):

// call with one parameter (using the Action<T> delegate of the framework
bool success = TimedMethodCaller(new Action<int>(TestMethod), 100, "text");

// call with several parameters using custom delegate that is defined like this:
// public delegate void SampleDelegate(string text, int numeric);
bool success = TimedMethodCaller(new SampleDelegate(TestMethod), 100, "text", 1);

关于c# - 我可以编写一个通用方法来调用超时的其他方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1468550/

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