How to call a long method in a new thread to keep the UI running in C#

16,111

Solution 1

using System.Threading;
new Thread(() => 
{
    Thread.CurrentThread.IsBackground = true; 
    /* run your code here */ 
    Console.WriteLine("Hello, world"); 
}).Start();

Solution 2

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:

Share:
16,111

Related videos on Youtube

0xFF
Author by

0xFF

Updated on June 04, 2022

Comments

  • 0xFF
    0xFF almost 2 years

    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.

    • Kyle C
      Kyle C about 11 years
      can you show what your current code is doing (starting a new thread?)
  • 0xFF
    0xFF about 11 years
    Alright let me try that.
  • User 12345678
    User 12345678 about 11 years
    That's some ugly code ...
  • 0xFF
    0xFF about 11 years
    Nope, it gives me "The calling thread must be STA, because many UI components require this", like a couple of methods I tried.
  • ChrisF
    ChrisF about 11 years
    @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.
  • 0xFF
    0xFF about 11 years
    @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()