创建矩形时,调用线程必须是STA

时间:2014-05-13 12:51:22

标签: c# wpf

您好我尝试在wpf应用程序中创建一个矩形,我收到了这个错误,我尝试使用Google搜索但是它没有用。

错误:

The calling thread must be STA, because many UI components require this.

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.Threading;

namespace Game
{
    class Engine
    {
        #region Members

        private Thread _render;

        #endregion

        public Engine()
        {
            _render = new Thread(new ThreadStart(Render));
            _render.Start();
        }

        private void Render()
        {
            while (true)
            {
                Rectangle rect = new Rectangle();
            }
        }
    }
 }

我认为这会解决它:

Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() => this.progressBar.Value = 50));

但是这并没有消除使用不同线程的目的,因为所有渲染仍然会在主线程上完成。

另一个问题:

我试图绘制1比1的矩形并检测碰撞,如果他们"跌倒"彼此相关(一个循环设置它们的x--)。 我也可以用像素做这个吗?

1 个答案:

答案 0 :(得分:0)

应始终在主线程上执行渲染。这是Windows / Win32中的设计。

由于Win32的原始设计(涉及到窗口的句柄,也就是hWnd'),调用绘制操作的线程必须与进行实际绘制的线程相同。

关于Threading model and WPF,MSDN上有一篇很好的文章。

相关问题