WPF多线程问题求教大神解答,在线等!
小白才开始用WPF,要做一个点击当前图片然后出现一个新窗体,因为新窗体加载数据有点多,想在新窗体没有出现之前做一个loading的效果。但是对多线程了解不多也不知道WPF中的这种多线程该怎么处理。求大神指教啊啊啊啊啊啊啊啊啊啊啊啊啊啊
private void gameImage1_MouseDown(object sender, MouseButtonEventArgs e)
{
try{
ShowLoading(true);
if (image.MakerId != null)
{
string[] str=new string[]{image.MakerId,image.Banner};
thread = new Thread(new ParameterizedThreadStart(gameLaunch));
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start(str);
}
}catch{}
finally
{
ShowLoading(false);
}
}
private void gameLaunch(object obj)
{
string[] str = obj as string[];
int game = int.Parse(str[0]);
string brandName = str[1];
WindXLive wind = new WindXLive();
wind.Show();
System.Windows.Threading.Dispatcher.Run();
return;
}
private void ShowLoading(bool isShow)
{
if (isShow)
{
loading.Visibility = Visibility.Visible;
}
else
{
loading.Visibility = Visibility.Collapsed;
}
}
我现在是loading做了个用户控件,放在别的地方loading可以转动,但是放在这里可能是加载数据占用了线程,loading一直卡住不动
[解决办法]
例如
前台,后面记得给和夸全部的,为了显示挡住全屏的效果
<Window x:Class="WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid x:Name="aaa" Grid.RowSpan="4" Visibility="Collapsed">
</Grid>
</Grid>
</Window>
<UserControl x:Class="WPF.UC"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid Height="200" Width="300">
<Label>Loding......</Label>
</Grid>
</UserControl>
在第一个页面的后台代码
[code=csharp]using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WPF
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
Thread t;
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
t = new Thread(new ThreadStart(show));
t.Start();
}
void show()
{
this.aaa.Dispatcher.Invoke(new Action(() =>
{
this.aaa.Children.Add(new UC());
this.aaa.Visibility = Visibility.Visible;
}));
//相当于做其他的事情
Thread.Sleep(3000);
this.aaa.Dispatcher.Invoke(new Action(() =>
{
this.aaa.Visibility = Visibility.Collapsed;
}));
t.Abort();
}
}
}