繁体   English   中英

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

[英]The calling thread must be STA when creating rectangles

您好,我尝试在wpf应用程序中创建一个矩形,但收到此错误,但尝试对其进行谷歌搜索,但没有成功。

错误:

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--设置)。 我也可以用像素吗?

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

由于Win32的原始设计(涉及到Windows的句柄,也称为hWnd的句柄),因此调用绘画操作的线程必须与进行实际绘画的线程相同。

在MSDN上有一篇不错的文章,关于线程模型和WPF

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM