简体   繁体   English

C#并行执行多个任务

[英]C# Execute Multiple Tasks in Parallel

I'm building an application that connects to a server, which takes a good 8 seconds to do, so I decided to launch a loading screen window in the meantime. 我正在构建一个连接到服务器的应用程序,这需要8秒钟才能完成,因此我决定同时启动一个加载屏幕窗口。

I want the loading screen to display a spinning wheel that spins as the application is connecting. 我希望加载屏幕显示一个在应用程序连接时旋转的旋转的车轮。

The problem is that when I try it out, the wheel locks and doesn't spin. 问题是,当我尝试一下时,车轮会锁定并且不会旋转。 The reason is that the app is busy connecting to the server, so it's keeping the wheel from spinning. 原因是该应用程序正忙于连接到服务器,因此可以防止旋转。 As soon as the application successfully connects, the wheel starts spinning. 一旦应用程序成功连接,轮子就会开始旋转。

If I get them to run asynchronously, I'm worried that the wait time would increase. 如果我让它们异步运行,我担心等待时间会增加。 So, I'm wondering what's the most efficient way that would allow both tasks to run in parallel. 因此,我想知道哪种最有效的方法可以使两个任务并行运行。

I'm using the mahapps progress ring 我正在使用mahapps进度环

For a scenario like yours, I would highly suggest you take a look at Asynchronous programming with async and await . 对于像您这样的场景,我强烈建议您看一下使用async和await进行异步编程

Here is a good resource for that https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/ 这是一个很好的资源, https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/async/

Asynchronous and parallel are two different things. 异步和并行是两个不同的事物。 In this case you want to display the spinning wheel and connect to the server in parallel. 在这种情况下,您要显示纺车并并行连接到服务器。 This means that you will have to connect to the server on another thread than the UI thread where the spinning wheel is displayed. 这意味着您必须在显示转轮的UI线程之外的其他线程上连接到服务器。 The UI thread cannot both update the wheel and connect to the server simultaneously. UI线程无法同时更新轮子和同时连接到服务器。

The preferred way to write multithreaded and parallel code in .NET is to use the Task Parallel Library (TPL) . 在.NET中编写多线程和并行代码的首选方法是使用任务并行库(TPL) You could start a task and await it using the async / await keywords that were introduced in C#5/.NET Framework 4.5 like this: 您可以使用C#5 / .NET Framework 4.5中引入的async / await关键字来启动任务并等待它,如下所示:

spinningWheel.Visibility = Visibility.Visible;
await Task.Run(()=> { /* connect to the server here... */ });
spinningWheel.Visibility = Visibility.Collapsed; //the server is connected

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM