我在winform中托管的WPF控件有Menu和一些标签。 WPF控件连接到Internet以下载一些数据。 我将代码分为两步 首先只设置控件属性 第二个连接到网络 第二个在线程内部运行, 但是在WPF控件完成他的两个步骤之前,Winform控件不会在表单上发生。
我尝试了许多方法使其成为可线程的 但是所有的方式都去了同一个目的地。
CODE 1-加载WPF控件
private void MDI_Load(object sender, EventArgs e)
{
MenuManager.FillMenu(MainMenu); // I have filled WinForm Menu first, but it doesn't appear until WPF finish
#region = WPF Control =
wpfManager.AddweatherControl();
wpfManager.weatherManager.Start(); // This have to run in another thread
#endregion
}
2- wpfManager.weatherManager.Start
public void Start()
{
//var tsk = System.Threading.Tasks.Task.Factory.StartNew(GetWeather);
//tsk.ContinueWith(t => { MessageBox.Show(t.Exception.InnerException.Message); },
// System.Threading.CancellationToken.None, System.Threading.Tasks.TaskContinuationOptions.OnlyOnFaulted,
// System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext());
//System.Threading.Thread t = new System.Threading.Thread(
// () => weatherControl.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(GetWeather))
// );
//t.SetApartmentState(System.Threading.ApartmentState.STA);
//t.Start();
weatherControl.Dispatcher.BeginInvoke(new Action(GetWeather), new object[] { });
}
void GetWeather()
{
#region = Weather =
Yweather.Getweather(UserManager.CurrentUser.Preferences.WeatherCity);
if (Yweather.Online && Yweather.IDayForecast.Count > 0)
{
weatherControl.CurrentDegree.Text = Yweather.IDayForecast[0].CurrentTemperature.ToString();
weatherControl.WeatherTypeName.Text = Yweather.IDayForecast[1].WeatherText;
weatherControl.AllDayDegree.Text = Yweather.IDayForecast[1].LowTemperature + " - " + Yweather.IDayForecast[1].HighTemperature;
weatherControl.WeatherType.Source = wpfManager.BitmapToImageSource(Yweather.IDayForecast[0].Image);
xWeatherDay weatherday1 = weatherControl.OhterDaysPanel.Children[0] as xWeatherDay;
weatherday1.AllDayDegree.Text = Yweather.IDayForecast[2].LowTemperature + " - " + Yweather.IDayForecast[2].HighTemperature;
weatherday1.WeatherType.Source = wpfManager.BitmapToImageSource(Yweather.IDayForecast[2].Image);
}
else
{
weatherControl.CurrentDegree.Text = "0";
weatherControl.WeatherTypeName.Text = "NAN";
weatherControl.AllDayDegree.Text = "0 - 0";
weatherControl.WeatherType.Source = wpfManager.BitmapToImageSource(Yweather.OfflineImage);
}
#endregion
}
答案 0 :(得分:1)
从您发布的代码看起来,延迟是由于在UI线程上运行GetWeather
。假设weatherControl
是WPF控件的一个实例,它在UI线程上运行,因为这是其调度程序所属的线程。
如果要在后台线程上运行代码,一种简单的方法是使用BackgroundWorker。你可以使用这样的东西:
public void Start()
{
var worker = new BackgroundWorker();
worker.DoWork += (sender, args) =>
{
GetWeather();
// put the results of getting the weather in to args.Result
};
worker.RunWorkerCompleted += (sender, args) =>
{
// use args.Result to update the UI
};
worker.RunWorkerAsync();
}
DoWork
事件处理程序中的代码在后台线程上运行,而RunWorkerCompleted
事件处理程序中的代码在UI线程上运行。