本文介绍了C#/ WPF:并行运行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我在主窗口中有一个用户控件,带有一个按钮(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();}推荐答案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:并行运行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-20 00:06