C#/ WPF:并行运行方法 [英] C#/WPF: run method parallel

查看:223
本文介绍了C#/ WPF:并行运行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在主窗口中有一个用户控件,带有一个按钮(Button1)。

Button1_click事件开始从webservice获取数据(运行> 1小时)。



减少想要运行10个任务来获取数据的时间。



在我的例子中,DoWork()方法可以不能马上开始。

在完成Button1_click事件后开始。

所以后期处理没有数据。



如何实现等待函数等待所有线程完成?



我尝试过:



UserControl:

I have an user control in the main window with a button (Button1).
The Button1_click event starts to fetch data from a webservice (runs >1 hour).

To reduce time a want to run 10 tasks to fetch the data.

In my example the method DoWork() does not start immediatly.
It starts after the Button1_click event is done.
So the post process has no data.

How can I implement the wait function to wait until all threads are finished?

What I have tried:

UserControl:

List<string> fetchedData = new List<string>();

private void Button1_Click(object sender, System.Windows.RoutedEventArgs e)
{
    fetchedData.Clear();
    FetchData();

    // problem: 
    // (pseudo code) wait until all data is fetched
    while(true) { break; }

    // Post process
    foreach (var item in fetchedData) {
      // do something with the data (complete data list!)
    }
}

private void FetchData() 
{
  var threads = new Thread[10];

  for (int segment = 0; segment <= 9; segment++)
  {
    var worker = new ThreadStart(
        ()=>this.Dispatcher.BeginInvoke(
            DispatcherPriority.Normal,
            (ThreadStart)delegate ()
            {
                DoWork(iSegment); //executed AFTER exiting the button1_click event
            }
        )
    );

    threads[segment] = new Thread(worker);
    threads[segment].Start();                     
  }
}

private void DoWork (int segment) {
   fetchedData.Add( Helpers.GetWebserviceData(segment) );

   // output some data to the mainWindow to see the actual process
   Helpers.mainWindow.LabelStatus.Content = "Current segment: " + i.ToString();
}

推荐答案

看看这个:使用异步和等待进行异步编程(C#)| Microsoft Docs [ ^ ]并观看此视频: C#和Visual Basic的异步最佳实践 - YouTube [< a href =https://www.youtube.com/watch?v=hbpRMREBbhQ\"target =_ blanktitle =New Window> ^ ]
Have a look at this: Asynchronous Programming with async and await (C#) | Microsoft Docs[^] and watch this video: Async Best Practices for C# and Visual Basic - YouTube[^]


Stephen Cleary也有很多关于.NET中的异步编程的文章: Async and Await [ ^ ]
Stephen Cleary has great articles too about Asynchronous Programming in .NET: Async and Await[^]


感谢您的评论。我已经构建了一个简单的示例,它调用了一些延迟方法。输出按正确的顺序排列(由于延迟不同)。



我现在的问题是:

我有一个网络服务在外部静态类中(见下文)。

这个包装器没有async关键字,webservice客户端没有异步调用(webreference to external service)。



将Wrapper放在实例类中是否有帮助,以便每个任务调用都是自己的包装器实例?



Thanks for your comments. I have build a simple example which calls some methods with delays. The output is as expected in the right order (due to the different delays).

My Problem is now:
I have a webservice in a external static class (see below).
This wrapper has no async keyword and there is no async call in the webservice client (webreference to external service).

Would it help to put the Wrapper in a instanced class so that the every task calls is own instance of the wrapper?

public static class Wrapper {
   public static string CallWebservice(string param) {
      var client = new Webservice.Client();
      // takes up to 3 seconds per call
      return client.Method(param);
   }
}




using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace AsyncTest
{
    public static class Helpers
    {
        public static MainWindow mainWindow = null;
    }

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Helpers.mainWindow = this;
        }

        public static void AddLog(string text)
        {
            Helpers.mainWindow.Dispatcher.Invoke(
                () => Helpers.mainWindow.LblOutput.Content += DateTime.Now.ToString() +


这篇关于C#/ WPF:并行运行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆