Jeg har skrevet følgende stykke eksempel-kode til dig for en Windows form med en knap og en multiline-textbox, som illustrerer, hvordan man benytter Invoke/InvokeRequired.
private void button1_Click(object sender, EventArgs e)
{
FileStream s = new FileStream(@"c:\\temp\\output.txt", FileMode.Open, FileAccess.Read, FileShare.Read, 256, true);
AsyncCallback callback = new AsyncCallback(EndReadCallback);
State state = new State(s);
s.BeginRead(state.ReadArray, 0, state.ReadArray.Length, callback, state);
}
private void EndReadCallback(IAsyncResult res)
{
State state = (State) res.AsyncState;
int count = state.File.EndRead(res);
string text = System.Text.Encoding.UTF8.GetString(state.ReadArray);
OpdaterTextBox(text);
state.File.Close();
}
delegate void OpdaterTextBoxDelegate(string text);
private void OpdaterTextBox(string text)
{
if (InvokeRequired)
Invoke(new OpdaterTextBoxDelegate(OpdaterTextBox), new object[] { text });
else
textBox1.Text = text;
}
private class State
{
byte[] readArray;
FileStream file;
public State(FileStream file)
{
readArray = new byte[256 * 1024];
this.file = file;
}
public byte[] ReadArray { get { return readArray; } }
public FileStream File { get { return file; } }
}
Håber, det hjælper :-)
:-) Jakob.