我的建議是將所有的事件發生在隊列中。我認爲你的問題發生了,因爲當一個事件觸發時,你調用一個方法,如果該方法在下一個事件發生時還沒有完成,它不能再被調用。 創建一個隊列並將事件發生在那裏,然後創建一個線程,等待隊列填充,然後將其取出。
樣品:
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
using System.Timers;
using Timer = System.Timers.Timer;
class Program
{
private static Queue<My_Event> EventQueue;
private static Timer t = new Timer(10);
static void Main(string[] args)
{
Task thread = new Task(MarkStuffYellow);
EventQueue = new Queue<My_Event>();
t.Elapsed += t_Elapsed;
t.Start();
t.AutoReset = true;
}
static void t_Elapsed(object sender, ElapsedEventArgs e)
{
EventQueue.Enqueue(new My_Event(sender, e));
}
private static void MarkStuffYellow()
{
/// !!! While (true) is not an solution, if you do it like this,
/// your CPU will be full !!!
while (true)
{
if (EventQueue.Any())
{
My_Event myEvent = EventQueue.Dequeue();
var sender = myEvent.Sender;
var e = myEvent.E;
/// Do Stuff with your event
}
}
}
}
/// Needed to save your event
internal class My_Event
{
public My_Event(object sender, ElapsedEventArgs e)
{
this.Sender = sender;
this.E = e;
}
public object Sender;
public ElapsedEventArgs E;
}
}
謝謝 - 你能可能指向我一個例子嗎? – jidl 2015-03-20 04:57:37