簡體   English   中英

在創建 window 句柄之前,無法在控件上調用 c# Invoke 或 BeginInvoke System.Threading.Thread

[英]c# Invoke or BeginInvoke cannot be called on a control until the window handle has been created System.Threading.Thread

不是Windows下的線程專家。 我有一個 Main WinForm 在它的 ctor 中打開一個子表單。

public partial class Main : Form
{
    public Main()
    {
        InitializeComponent();

        ImgRxUI formStart = new ImgRxUI();
        formStart.MdiParent = this;
        formStart.WindowState = FormWindowState.Maximized;
        formStart.Show();
    }

ETC..

ImgRxUI 表單(子表單)啟動一個傳遞給 2 個操作(簡單形式的委托)的線程。

 public partial class ImgRxUI : Form
{

    private ImgReceiver oImgReceiver = null;

    public ImgRxUI()
    {
        InitializeComponent();

        this.WindowState = FormWindowState.Maximized;
        this.ShowIcon = false;

        oImgReceiver = new ImgReceiver(UpdateImage, Log);
        oImgReceiver.startService();

    }



    public void UpdateImage(byte[] ProtocolType)
    {
       ...do stuff...

    }

    public void Log(string Text)
    {
        this.Invoke((MethodInvoker)delegate
        {
            LogMethod(Text);
            tLog.ScrollToCaret();
        });

    }

    private void LogMethod(string Text)
    {
        tLog.AppendText(Text + Environment.NewLine);
    }

正如我所說的 ImgReceiver 啟動了一個在套接字上偵聽的線程......

 public class ImgReceiver
{

    private Action<byte[]> ImgReceived;
    private Action<string> Log;
    private System.Threading.Thread Thread_ImgReceiver = null;

    public ImgReceiver(Action<byte[]> ImageReceivedDelegate, Action<string> LogDelegate)
    {
        
        this.ImgReceived = ImageReceivedDelegate;
        this.Log = LogDelegate;
    }

    public void startService()
    {
        Thread_ImgReceiver = new System.Threading.Thread(startListening);
        Thread_ImgReceiver.IsBackground = true;
        Thread_ImgReceiver.Start();
    }

    [SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
    public void killService()
    {
        Thread_ImgReceiver.Abort();
        System.Threading.Thread.Sleep(1000);
    }

    public void startListening()
    { ...do stuff...}

當我關閉 ImgRxUI 表單時,表單本身的以下事件被調用

 private void ImgRxUI_FormClosing(object sender, FormClosingEventArgs e)
    {
        oImgReceiver.killService();            
    }

聽起標題中的錯誤。

什么?

塔克斯

將 kill Service 方法更改為

[SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
public void killService(Action action)
{
   action.Invoke();
   System.Threading.Thread.Sleep(1000);
}

將訪問級別 Thread_ImgReceiver 更改為 public

public System.Threading.Thread Thread_ImgReceiver = null;

並調用 killService 到

private void ImgRxUI_FormClosing(object sender, FormClosingEventArgs e)
{  
    oImgReceiver.killService(new Action(delegate { oImgReceiver.Thread_ImgReceiver.Abort(); }));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM