c# - 跨线程控制

标签 c# picturebox multithreading

我目前正在尝试创建一个计时器,它每隔几毫秒就会运行一段代码。问题是我希望能够修改在与计时器相同的线程上创建的图片框的位置,我最终得到了调用对象错误,即使它不是在原始线程上创建的?

private void frmMain_Load(object sender, EventArgs e)
{
    //Update Timer Thread
    UpdateThread = new Thread(new ThreadStart(UpdateWindow));
    SleepTime = (int)1000/MaxFps;
    UpdateThread.Start();        
    //.....
}

delegate void SetTextCB(string text);
delegate void SetControl(Control cntrl);

public void TimerThread()
{
    //Controls
    PictureBox TestPicBox;

    //Test TestPicBox
    TestPicBox = new PictureBox();
    TestPicBox.Image = Image.FromFile(TestImage.bmp");
    TestPicBox.Top = 20;
    TestPicBox.Left = 20;
    TestPicBox.Width = 64;
    TestPicBox.Height = 64;
    FilePanelControl(TestPicBox);

    while (true)
    {
        //--Sleep
        Thread.Sleep(SleepTime);
        //--FPS
        if (DateTime.Now.ToString("HH:mm:ss") != SystemTime)
        {
            if (blnShowFps) { lblFpsTextsSet(UpdateFps.ToString() + "-FPS"); }
            else { lblFpsTextsSet(""); }
            SystemTime = DateTime.Now.ToString("HH:mm:ss");
            UpdateFps = 0;
        }
        UpdateFps++;
        //Sleep Time
        SleepTime = (int)1000 / MaxFps;

        //Do UpDate Logic
        TestPicBox.location = new point(10,10);
    }
}

//--Add Control
private void FilePanelControl(Control added)
{
    if (this.FilePanel.InvokeRequired)
    {
        SetControl d = new SetControl(FilePanelControl);
        this.Invoke(d, new object[] { added });
    }
    else
    {
        this.FilePanel.Controls.Add(added);
    }
}

//--lblFps.text
private void lblFpsTextsSet(string text)
{
    if (this.lblFPS.InvokeRequired)
    {
        SetTextCB d = new SetTextCB(lblFpsTextsSet);
        this.Invoke(d, new object[] { text });
    }
    else
    {
        this.lblFPS.Text = text;
    }
}

希望我不必调用我在此线程上声明的每个控件,因为计划是制作一个图片框列表,以便用户可以根据需要添加图片框。

感谢您的帮助。

最佳答案

您应该使用 System.Windows.Forms.Timer 而不是创建自己的线程。

这样,一切都已经在 UI 线程上了。

关于c# - 跨线程控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9153838/

相关文章:

mysql - 将图像存储到数据库 blob;从数据库检索到 Picturebox

c# - 发布设计代码来管理对象

C++ Windows 窗口是否强制唤醒等待中的线程?

c - 以基本方式使用线程的段错误

c# - 事件设计器中未启用 ReportViewer 控件。 - Visual Studio 2017

c# - Powershell:无法与 .Net 程序集中存储的表单交互

c# - MVC3 中的 CSS 背景图像——续

c# - 用户控件 c# 动态添加

c# - 等待后台 worker 完成而不阻塞 UI 线程

VS2005 中的 C# : what do the following types default to in C#?