【问题标题】:Invoke in static multithreading instance在静态多线程实例中调用
【发布时间】:2012-04-13 18:21:36
【问题描述】:

我要做的是在当前表单的某个位置获取像素颜色。但是,我调用该方法的点是在一个单独的线程中。当我运行应用程序时,我收到一个错误:

跨线程操作无效:从 线程不是创建它的线程。

线程代码:

Thread drawThread;
drawThread = new Thread(drawBikes);

drawBikes 代码:

public void drawBikes()
{
    MessageBox.Show("Bike "+bike.color.ToString()+": "+Form1.ActiveForm.GetPixelColor(bike.location.X, bike.location.Y).ToString());
}

这里是 GetPixelColor 方法(在一个单独的静态类中):

public static class ControlExts
{
    public static Color GetPixelColor(this Control c, int x, int y)
    {
        var screenCoords = c.PointToScreen(new Point(x, y));
        return Win32.GetPixelColor(screenCoords.X, screenCoords.Y);
    }
}

我在哪里调用调用?

【问题讨论】:

标签: c# .net multithreading invoke


【解决方案1】:

您需要从与 UI 交互的任何其他线程调用 Invoke。在您的情况下, drawBikes() 正在尝试更新 UI。试试这个:

    public void drawBikes()
    {
        if (InvokeRequired)
        {
            this.Invoke(new MethodInvoker(drawBikes));
            return;
        }
        // code below will always be on the UI thread
        MessageBox.Show("Bike "+bike.color.ToString()+": "+Form1.ActiveForm.GetPixelColor(bike.location.X, bike.location.Y).ToString());

    }

【讨论】:

    【解决方案2】:

    将您的代码放入BeginInvoke

    有点像

                public static class ControlExts
                {
                          public static Color GetPixelColor(this Control c, int x, int y)
                          {
                             this.BeginInvoke(new Action(() =>
                              {
                              var screenCoords = c.PointToScreen(new Point(x,y));
                              return Win32.GetPixelColor(screenCoords.X, screenCoords.Y);
                             }));
    
                           }
               }
    

    【讨论】:

      猜你喜欢
      • 2012-03-14
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      相关资源
      最近更新 更多