2016-06-09 41 views
1

現在,在我的UserControl中,我有一個按鈕單擊事件啓動一個線程。我從使用Abort()開始,並試圖將我的線程轉換爲後臺進程,以便在關閉父窗體時關閉它們。我的代碼是:c#後臺線程在UserControl中運行時出現錯誤

public Thread t; 
private void btnInitiate_Click(object sender, EventArgs e) 
    { 
     UDPListener myListiner = new UDPListener(this); 
     t.IsBackground = true; 
     t = new Thread(() => myListiner.SpreadValue(myCurrentPort, firstTicker, secondTicker, myBeta)); 
     t.Start(); 
    } 

但是當我運行應用程序,我從t.IsBackground=true一個錯誤的地方說:「不設置到對象的實例對象引用」。我想知道我在這種情況下出錯了。

+0

啓動任務後,您的方法已完成,但任務仍在運行myListiner超出範圍。在任務內創建監聽器 – Peter4499

回答

1

你只需要改變你的代碼行順序:

... 
t = new Thread(() => myListiner.SpreadValue(myCurrentPort, firstTicker, secondTicker, myBeta)); 
t.IsBackground = true; 
... 

因爲你需要實例化你的線程,然後才使用它。

+0

謝謝,這工作。很簡單,我覺得很傻。 –

+0

不客氣。我很樂意提供幫助。 – MaKCbIMKo

相關問題