Category Archives: Code

Simple, easy way to avoid UI from freezing in Windows Forms / WPF apps

It’s always been a pain point to not have the UI freeze, when some long running background task is going on in Windows Forms or WPF applications. We’ve been used to using the infamous BackgroundWorker to achieve this, however with Task Parallel Library it’s so much succinct to manage this.

      Task.Factory.StartNew(() =>
        return DoWork();
      .ContinueWith(antecedent =>
        catch (AggregateException ae)
          ae.Handle((x) =>
            statusStrip1.Items[0].Text = "Done.";
            ViewerProgressBar.Visible = false;
            return false; // Let anything else stop the application.
      }, TaskScheduler.FromCurrentSynchronizationContext());