Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 618
0xFF Avatar asked Dec 15 '22 14:12

0xFF


1 Answers

using System.Threading;
new Thread(() => 
{
    Thread.CurrentThread.IsBackground = true; 
    /* run your code here */ 
    Console.WriteLine("Hello, world"); 
}).Start();
like image 192
Priyank Thakkar Avatar answered May 17 '23 19:05

Priyank Thakkar