wpf 如何在新线程中调用长方法以保持 UI 在 C# 中运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14761687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 07:24:35  来源:igfitidea点击:

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

c#wpfmultithreadinguser-interfacereporting-services

提问by 0xFF

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().

我有一个 WPF 应用程序,其中包含一个填充有用户的组合框、一个显示所选用户的一些数据的网格和一个调用 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.

DoTimeSheetReport() 做了一些工作,然后打开一个带有 SSRS 报告的新窗口。一切正常,但该方法需要很长时间才能完成,主要是因为报告,这意味着我的 UI 变得无响应。我尝试了几种方法来启动一个新的线程/任务,但所有这些都阻塞了 UI 的线程。我可能做错了什么,但我不知道。

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

为了不阻塞 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.

在这部分使用 backgroundWorker 做到了。感谢您的帮助。

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

@LuisQuijada:那行得通,发布一个答案,这样我就可以接受了。

回答by Priyank Thakkar

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

回答by Yusubov

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:

作为起点,您可以查看帖子和/或 MSDN 文章中的建议链接: