A191919 A191919 - 1 month ago 13
C# Question

Task.Factory.StartNew delay without ui freez

When I am use

Thread.Sleep
in
UpdateGuItemsAsync
program freez for 10 second because thread is blocked. If I use
Task.Delay
in 'UpdateGuItemsAsync' code executes immediately without pause. I expect to get delay before list update without UI freezing. How to do this in .net 3.5?

TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(UpdateGuItemsAsync, CancellationToken.None, TaskCreationOptions.None, uiScheduler);


public void UpdateGuItemsAsync()
{
System.Threading.Thread.Sleep(10000);
for (int i = 0; i < 100; i++)
{
Gu45Document gu45Document = new Gu45Document();
gu45Document.Form = "EU-45";
Gu45Documents.Add(gu45Document);
}
}

Answer

You can use System.Windows.Forms.Timer which will not block the UI while waiting 10 seconds :

 public void UpdateGuItemsAsync()
 {
    System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
    timer.Interval = 10000;
    timer.Tick += (sender, args) => 
    {
        timer.Stop();
        for (int i = 0; i < 100; i++)
        {
            Gu45Document gu45Document = new Gu45Document();
            gu45Document.Form = "EU-45";
            Gu45Documents.Add(gu45Document);
        }
    };
    timer.Start();  
 }