4

I have WPF application with a combobox filled with Users, a grid showing some data for the selected User and a button that calls DoTimeSheetReport().

DoTimeSheetReport() does some work and then opens a new window with a SSRS report. Everything works fine but the method takes a long time to complete, mostly because of the report, which means my UI becomes unresponsive. I tried a couple of ways to start a new thread/task but all of them are blocking the UI's thread. I'm probably doing something wrong but I have no idea.

What's the best way to call a long method in order to not block the UI?

EDIT

I changed my code to isolate the time-consuming part.

reportViewer.SetPageSettings(reportConfiguration.PageSettings);

Using a backgroundWorker on this part did it. Thank you for your help.

@LuisQuijada: That worked, post an answer so I can accept it.

0xFF
  • 808
  • 1
  • 12
  • 33

2 Answers2

11
using System.Threading;
new Thread(() => 
{
    Thread.CurrentThread.IsBackground = true; 
    /* run your code here */ 
    Console.WriteLine("Hello, world"); 
}).Start();
Priyank Thakkar
  • 4,752
  • 19
  • 57
  • 93
  • Alright let me try that. – 0xFF Feb 07 '13 at 21:54
  • 1
    That's some ugly code ... – User 12345678 Feb 07 '13 at 21:55
  • Nope, it gives me "The calling thread must be STA, because many UI components require this", like a couple of methods I tried. – 0xFF Feb 07 '13 at 21:56
  • 1
    @fhlamarche - if you are calling UI elements from the code you want to put in the thread then you'll get this error message. Look into using events and dispatchers to marshal UI calls from background worker threads. – ChrisF Feb 07 '13 at 22:01
  • @ChrisF My method doesn't use any of it's parent's members. It instantiate a new windows with a reportViewer and just calls .Show() – 0xFF Feb 07 '13 at 22:08
1

In short: what you need to do is to look at how to use async calls.

As a start place you may look at suggested link in your post and/or the MSDN article:

Yusubov
  • 5,815
  • 9
  • 32
  • 69