WPF中多UI线程问题,子线程挂起后主线程也卡住
之前用WPF写多线程时,当子线程处理数据量大时,主线程就会有卡的现象,后来看到一篇文章“深入WPF -- Dispatcher(补)”,http://www.cnblogs.com/Zhouyongh/archive/2011/01/12/1933414.html,讲述了多UI线程的问题,用VisualTarget对象树进行连接,但是试了以后挂起子线程或者子线程处理大量数据时,仍然会卡,以下粘出代码,求各位大大帮忙,已经找了几天了,还没有解决办法--------------------编程问答-------------------- 竟然没有人理我,哪位神人帮帮我 --------------------编程问答-------------------- 再自己顶一下,处理多UI 线程的时候,子线程需要对textbox控件进行大量的数据更新操作,这样主界面就会卡死,直到子线程运算完成 --------------------编程问答-------------------- 还是没有人理我,或者不要上面的方式处理,有没有其他的处理办法 --------------------编程问答--------------------
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Window win = new Window();
VisualHost vh = new VisualHost();
HostVisual hostVisual = new HostVisual();
vh.Child = hostVisual;
win.Content = vh;
Thread thread = new Thread(new ThreadStart(() =>
{
VisualTarget visualTarget = new VisualTarget(hostVisual);
DrawingVisual dv = new DrawingVisual();
using (var dc = dv.RenderOpen())
{
//for (int i = 0; i < 100000; i++)
{
dc.DrawText(new FormattedText("UI from another UI thread",
System.Globalization.CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight,
new Typeface("Verdana"),
32,
Brushes.Black), new Point(10, 0));
}
}
visualTarget.RootVisual = dv;
Thread.Sleep(5000);
Dispatcher.Run(); //启动Dispatcher
}));
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
win.Show();
}
}
public class VisualHost : FrameworkElement
{
public Visual Child
{
get { return _child; }
set
{
if (_child != null)
RemoveVisualChild(_child);
_child = value;
if (_child != null)
AddVisualChild(_child);
}
}
protected override Visual GetVisualChild(int index)
{
if (_child != null && index == 0)
return _child;
else
throw new ArgumentOutOfRangeException("index");
}
protected override int VisualChildrenCount
{
get { return _child != null ? 1 : 0; }
}
private Visual _child;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Thread thread = new Thread(new ThreadStart(() =>
{
Window win = new Window();
VisualHost vh = new VisualHost();
HostVisual hostVisual = new HostVisual();
vh.Child = hostVisual;
win.Content = vh;
win.Show(); VisualTarget visualTarget = new VisualTarget(hostVisual);
DrawingVisual dv = new DrawingVisual();
using (var dc = dv.RenderOpen())
{
//for (int i = 0; i < 100000; i++)
{
dc.DrawText(new FormattedText("UI from another UI thread",
System.Globalization.CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight,
new Typeface("Verdana"),
32,
Brushes.Black), new Point(10, 0));
}
}
visualTarget.RootVisual = dv;
Thread.Sleep(5000);
Dispatcher.Run(); //启动Dispatcher
}));
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
}
应该放到线程中去创建吧 --------------------编程问答--------------------
也遇到同样的问题,请问你解决了吗?是怎么解决的? --------------------编程问答-------------------- 子线程更新父线程控件状态时不可取的 你可以在子线程中发送消息 然后父线程接受消息 自己处理更新
补充:.NET技术 , C#