2013-10-22 20 views
-1

我寫了一個簡單的文件流程序在C#中使用異步閱讀使用其主線程以外的線程爲其回調。但我越來越跨線程異常,當我嘗試在文本框中寫入我的文件內容。 這裏是我的程序:使用調用來訪問表單上的文本框

using System; 

namespace Filestream 
{ 
    public partial class Form1 : Form 
    { 
     FileStream fs; 
     byte[] fileContents; 
     AsyncCallback callback; 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void synbtn_Click(object sender, EventArgs e) 
     { 
      openFileDialog1.ShowDialog(); 
      callback = new AsyncCallback(fs_StateChanged); 
      fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true); 
      fileContents = new Byte[fs.Length]; 
      fs.BeginRead(fileContents, 0, (int)fs.Length, callback, null); 
     } 
     public void fs_StateChanged(IAsyncResult ar) 
     { 

       if (ar.IsCompleted) 
       { 
        *textBox1.Text = Encoding.UTF8.GetString(fileContents);* 
        fs.Close(); 
       } 
     } 

    } 
} 

與明星的部分是,我發現了exception.i試圖使用invoke,但我沒有luck.can有人糾正與這部分代碼的一部分調用所以我不會得到錯誤。 謝謝。

+0

我得到了我的答案。但有人可以指出我在線程中使用這個調用一個很好的教程?或只是爲我解釋? –

+0

當您在UI上更改文本,顏色或大小等內容時,必須使用創建元素的相同線程來完成此操作。 UI控件提供了一些幫助完成此操作的事情。 – Nick

回答

1

試試這個。

if(textbox1.InvokeRequired) 
{ 
    textbox1.Invoke(new MethodInvoker(() => textBox1.Text = Encoding.UTF8.GetString(fileContents))); 
} 
else 
{ 
    textBox1.Text = Encoding.UTF8.GetString(fileContents); 
} 
+0

這將失敗,如果fs_StateChanged恰巧從創建textbox1 – Nick

+0

@Nick感謝信息的線程調用。 –

+0

除非需要等待文本框更新,否則使用'BeginInvoke'而不是'Invoke'。請參閱http://msdn.microsoft.com/en-us/library/0b1bf3y3.aspx –

0

擴大對拉姆的回答

//Can this thread make updates to textbox1?  
if(textbox1.InvokeRequired) 
{ 
    //No then use the invoke method to update textbox1 
    textbox1.Invoke(new MethodInvokernew MethodInvoker(() => textBox1.Text = Encoding.UTF8.GetString(fileContents))); 
}else{ 
    //Yes then update textbox1 
    textBox1.Text = Encoding.UTF8.GetString(fileContents); 
} 

說明: 更新UI控件必須創建該UI控件的線程上完成。要測試當前線程是否被允許更新特定的UI控件,請調用控件上的InvokeRequired方法。調用然後可以用來調用一個方法使用線程,可以更新控制

相關問題