Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to add some text to list box using Task and I simply use a button and place in click event this code:

TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(() =>
{
    for (int i = 0; i < 10; i++)
    {
        listBox1.Items.Add("Number cities in problem = " + i.ToString());
        System.Threading.Thread.Sleep(1000);
    }
}, CancellationToken.None, TaskCreationOptions.None, uiScheduler);

but it does not work and UI locked until end of for loop.where is problem?

thanks :)

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

where is problem?

Well you're explicitly saying that you want to execute the task in the UI thread... and then you're sleeping within the task, so it's blocking the UI thread. How did you expect to be in the UI thread, but for Thread.Sleep not to cause a problem?

If you can use C# 5 and async/await, that would make things much easier:

private static async Task ShowCitiesAsync()
{
    for (int i = 0; i < 10; i++)
    {
        listBox1.Items.Add("Number cities in problem = " + i);
        await Task.Delay(1000);
    }
}

If you can't use C# 5 (as suggested by your tags), it's significantly trickier. You might be best off using a Timer:

// Note: you probably want System.Windows.Forms.Timer, so that it
// will automatically fire on the UI thread.
Timer timer = new Timer { Interval = 1000; }
int i = 0;
timer.Tick += delegate
{
    listBox1.Items.Add("Number cities in problem = " + i);
    i++;
    if (i == 10)
    {
        timer.Stop();
        timer.Dispose();
    }
};
timer.Start();

As you can see, it's pretty ugly... and it assumes you don't want to actually do any work between UI updates.

Another alternative would be to simulate your long-running task (sleeping at the moment) on a different thread using BackgroundWorker, and use ReportProgress to come back to the UI thread to add the list item.

share|improve this answer
 
thanks but I'm currently using C#-4 what can I do?In my main program I have not use Sleep I have some methods that are long running and I add Item after execute of them in list box such as Step 1 Completed... but this message does not show until running –  Kerezo Jul 2 at 5:54
 
@Kerezo: See my edits for two alternatives. But we don't really know what the bigger picture is - presumably you'll want to do things other than sleeping at some point. –  Jon Skeet Jul 2 at 5:55
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.