BackgroundWorker + Cross-Thread
Bonjour,
Voici un programme pour bien comprendre le fonctionnement du bgw et éviter le cross-thread.
J'ai un formulaire avec un textbox qui doit être mis à jour. Voici mon code, la seule mise à jour du textbox est toujours "test" et jamais "Yahoo". Pouvez-vous me dire ce je fais pour que ça ne foncionne pas ? Merci
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;
using ActiveDs;
using System.Threading;
namespace PCLife
{
public partial class Form1 : Form
{
delegate void SetTextIsCallingBack(string strTextToAppend);
public Form1()
{
InitializeComponent();
}
private void BckWrk_DoWork(object sender, DoWorkEventArgs e)
{
SetNewText("Yahoo!"); Thread.Sleep(2000);
SetNewText("Done"); BckWrk.Dispose();
}
private void SetNewText(string strTextToAppend)
{
if (txtResult.InvokeRequired)
{
this.Invoke(new SetTextIsCallingBack(this.SetNewText), new object[] { strTextToAppend }); return;
}
else
{
txtResult.AppendText("test" + Environment.NewLine); }
}
private void LastLogonTimeStamp_Click(object sender, EventArgs e)
{
if (!BckWrk.IsBusy)
{
BckWrk.RunWorkerAsync();
return;
} }
private void BckWrk_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// this.tbProgress.Value = e.ProgressPercentage;
// lbPourcent.Text = (e.ProgressPercentage.ToString() + "%");
}
private void txtResult_TextChanged(object sender, EventArgs e)
{
}
private void BckWrk_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
}
} |