[英]Using BackgroundWorker WPF and getting error: Cannot access a disposed object
我對多線程還很陌生,因此請原諒可能出現的任何明顯錯誤-我仍在學習!
我目前有一個程序,該程序使用TCPClient
和NetworkStream
從端口讀取數據,並將數據輸出到WPF程序中的text box
。 但是,當嘗試從stream
中多次讀取時,它會明顯降低程序運行速度,並且讀取的次數越多,打開程序所花費的時間就越長。 因此,我決定嘗試實現threading
並且嘗試使用Background Worker
。
這是我在MainWindow
擁有的代碼:
InitializeComponent();
try
{
client.Connect(address, port); //connect to the client
nwStream = client.GetStream(); //read in data from stream
readInTxtBox.Text = ("Connection Open");
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.RunWorkerAsync();
}
catch (SocketException ex)
{
readInTxtBox.Text = ex.ToString(); //write out the error
}
finally
{
client.Close();
}
這是worker_DoWork
和worker_RunWorkerCompleted
方法:
void worker_DoWork(object sender, DoWorkEventArgs e)
{
if (Dispatcher.CheckAccess())
{
ReadIn();
}
else
{
Dispatcher.BeginInvoke(new Action(() =>
{
ReadIn();
}));
}
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Dispatcher.BeginInvoke(new Action(() =>
{
OutputToTextBoxInput();
}));
}
單步執行時,它確實轉到worker_DoWork
上的Dispatcher.BeginInvoke
操作,並在ReadIn()
方法的第一行失敗:
private void ReadIn()
{
byte[] b = Utilities.ReadInBytes(client, nwStream); //fails here!
hex = Utilities.ConvertByteToHex(b);
nwStream.Close();
}
它在ReadInBytes
方法的以下行中fails
,並顯示錯誤: Cannot access a disposed object.
public static byte[] ReadInBytes(TcpClient client, NetworkStream nwStream)
{
byte[] bytesToRead = new byte[client.ReceiveBufferSize]; //FAILS HERE
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
ArraySegment<byte> segment = new ArraySegment<byte>(bytesToRead, 0, bytesRead);
return segment.ToArray();
}
client
和network stream
被聲明為public statics
。 使用invoke
和不使用invoke
時,我都遇到了這個問題。 我也嘗試了BeginInvoke
並且發生了相同的問題。 我們將不勝感激任何幫助以及對我哪里出錯了的任何解釋!
問題是,您將客戶端放置在finally塊中,但是在稍后運行的DoWork
方法中使用它。
要解決此問題,請在DoWork事件中創建,連接和克隆客戶端:)。
如評論中所述,您不應在DoWork方法中分派代碼! 只需致電ReadIn。 您想在后台運行代碼,以使GUI保持可回收狀態-將其推送到GUI線程毫無意義!
也不需要在RunWorkerCompleted事件處理程序中分派代碼,因為后台工作會為您完成代碼;)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.