control.invoke must be used to interact with controls created on a separate thread in .net CF





0/5 (0 vote)
On version 1 of the .NET Compact Framework, applications which attempted to update their user interface from a worker thread would typically hang. Having an application hang is an unpleasant user experience.
Control.Invoke must be used to interact with controls created on a separate thread. The first step to fix our snippet is to define a delegate.
public int c = 0;
private delegate void UpdateStatusDelegate();
Next, we add an implementation of a method that matches our delegate's signature
public void newload()
{
int j = 0;
for (int i = 0; i == j; i++)
{
Thread.Sleep(5000);
if (this.InvokeRequired)
{
// we were called on a worker thread
this.Invoke(new UpdateStatusDelegate(fncontrol) );
}
MessageBox.Show("working count: "+c+" " );
c++;
j++;
}
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new System.Threading.ThreadStart(newload));
t.Start();
t.IsBackground = true;
}
public void fncontrol()
{
this.textBox1.Text = c.ToString();
this.progressBar1.Value = c;
}
public void newload()
{
int j = 0;
for (int i = 0; i == j; i++)
{
Thread.Sleep(5000);
if (this.InvokeRequired)
{
// we were called on a worker thread
this.Invoke(new UpdateStatusDelegate(fncontrol) );
}
MessageBox.Show("working count: "+c+" " );
c++;
j++;
}
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new System.Threading.ThreadStart(newload));
t.Start();
t.IsBackground = true;
}
public void fncontrol()
{
this.textBox1.Text = c.ToString();
this.progressBar1.Value = c;
}
Full Code
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace sdpThread
{
public partial class Form1 : Form
{
public int c = 0;
private delegate void UpdateStatusDelegate();
public Form1()
{
InitializeComponent();
}
public void newload()
{
int j = 0;
for (int i = 0; i == j; i++)
{
Thread.Sleep(5000);
if (this.InvokeRequired)
{
// we were called on a worker thread
this.Invoke(new UpdateStatusDelegate(fncontrol) );
}
MessageBox.Show("working count: "+c+" " );
c++;
j++;
}
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new System.Threading.ThreadStart(newload));
t.Start();
t.IsBackground = true;
}
public void fncontrol()
{
this.textBox1.Text = c.ToString();
this.progressBar1.Value = c;
}
}
}
Join In Codeforum