Bir Görevlinin bir Zamanlayıcı tarafından neden iyi işlediğini, ancak bir Görev tarafından bir Zamanlayıcı'nın neden ortaya çıktığını açık bir şekilde açıklayamam.Timer Spawn Göreve Göre Görev ve Görev Spawn By Timer
İlgili tüm kodlar aşağıda yer almaktadır, böylece kolayca yeniden üretebilirsiniz.
Form.cs:
private void Form1_Load(object sender, EventArgs e)
{
ProcessDelayList list = new ProcessDelayList();
foreach (ProcessDelay p in list)
{
//this works
p.Start();
//this does NOT work
//Task.Factory.StartNew(() => p.Start());
}
}
ProcessDelayList.cs:
public class ProcessDelayList : List<ProcessDelay>
{
public ProcessDelayList()
{
Add(new ProcessDelay("Process 1", 2000));
Add(new ProcessDelay("Process 2", 4000));
Add(new ProcessDelay("Process 3", 6000));
Add(new ProcessDelay("Process 4", 8000));
Add(new ProcessDelay("Process 5", 10000));
}
}
ProcessDelay.cs:
public class ProcessDelay
{
private string name;
private int delay;
private Timer timer;
public ProcessDelay(string name, int delay)
{
this.name = name;
this.delay = delay;
}
public void Start()
{
timer = new Timer();
timer.Interval = delay;
timer.Tick += timer_Tick;
timer.Start();
}
private void timer_Tick(object sender, EventArgs e)
{
//these work either way, as long as the task
// is NOT spawn in the main loop.
//TimerProc();
TimerProcTask();
}
private void TimerProcTask()
{
Task.Factory.StartNew(() => TimerProc());
}
private void TimerProc()
{
timer.Stop();
MessageBox.Show(name, delay.ToString());
}
}
Yeni Görev'i kullanmaya çalışabilir misiniz (() => p.Start()) Start() ;? – thinklarge
@thinklarge: InvalidOperationException: Başlangıç, başlatılmış olan bir görevde çağrılmayabilir. – jsanalytics