gpt4 book ai didi

c# - 通过线程池中的计时器执行方法

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

在我的多线程 Web 应用程序中,我在 ThreadPool SomeMethod 中调用,这可能会引发异常。假设我想做几次尝试,如果它在第一次调用时导致异常。我决定在我的操作中使用 System.Timers.Timer 进行尝试。我可以使用下面的代码吗?安全吗?

static void Caller()
{
ThreadPool.QueueUserWorkItem(action =>
{
try
{
SomeMethod();
Console.WriteLine("Done.");
}
catch
{
var t = new System.Timers.Timer(1000);
t.Start();
var count = 0;
t.Elapsed += new System.Timers.ElapsedEventHandler((o, a) =>
{
var timer = o as System.Timers.Timer;
count++;
var done = false;
Exception exception = null;
try
{
Console.WriteLine(count);
SomeMethod();
done = true;
}
catch (Exception ex)
{
exception = ex;
}
if (done || count == 10)
{
Console.WriteLine(String.Format("Stopped. done: {0}, count: {1}", done, count));
t.Stop();
if (!done) throw exception;
}
});
}
});
Thread.Sleep(100000);
}

static void SomeMethod()
{
var x = 1 / new Random().Next(0, 2);
}

最佳答案

您应该在使用后处理每个 Timer,这是肯定的。但是,也许你可以做更简单的事情:

static void Main()
{
ThreadPool.QueueUserWorkItem(action =>
{
while (TrySomeMethod() == false)
Thread.Sleep(1000);
});

// wait here
Console.Read();
}

static bool TrySomeMethod()
{
try
{
SomeMethod();
return true;
}
catch
{
return false;
}
}

关于c# - 通过线程池中的计时器执行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6607495/

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