मैं स्पष्ट रूप से स्पष्ट रूप से समझा नहीं सकता कि टाइमर द्वारा किए गए कार्य को ठीक क्यों काम करता है लेकिन कार्य द्वारा टाइमर स्पॉन नहीं होता है।टाइमर द्वारा कार्य और कार्य स्पॉन द्वारा टाइमर स्पॉन
सभी प्रासंगिक कोड नीचे शामिल हैं ताकि आप इसे आसानी से पुन: उत्पन्न कर सकें।
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());
}
}
क्या आप नए कार्य (() => p.Start()) का उपयोग करने का प्रयास कर सकते हैं। प्रारंभ() ;? – thinklarge
@thinklarge: InvalidOperationException: प्रारंभ से पहले से शुरू किए गए कार्य पर प्रारंभ नहीं किया जा सकता है। – jsanalytics