【发布时间】:2011-09-30 06:03:52
【问题描述】:
在我的多线程 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);
}
【问题讨论】:
-
考虑 System.Timers.Timer 已经在其他线程上运行。它不同于 System.Windows.Forms.Timer
-
@Tigran 据我了解,我的解决方案是 Thread.Sleep。
-
我试过了,效果很好。有没有办法让用户也可以取消 SomeMethod 的执行?
-
Brr,这里不使用 Sleep() 没有意义。
标签: c# .net multithreading timer threadpool