Wednesday, October 27, 2010

Thread Safety Example

Thread Safety

It's new in .Net 2.0.
It's used to prevent DeadLock.
Thread Safety is a technique that allows us cross thread operation in a safe manor.
Important properties:
→ CheckForIllegalThreadCalls: It's bydefault True. Gets or Sets a value indicating whether to calls on the wrong thread that access a control's System.Windows.Forms.Control.Handle Property when an application is being debugged.
→ InvokeRequire(T, F): it is a property of Control. Default value is true. It means control is in different domain and calling is being done from different domain.

drag and drop two textbox and a button on the page.

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.Threading;

namespace Test_Thread1
{
public partial class Form1 : Form
{
ThreadStart ts1,ts2;
Thread th1,th2;
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
ts1 = new ThreadStart(abc);
th1 = new Thread(ts1);
th1.Start();
ts2 = new ThreadStart(xyz);
th2 = new Thread(ts2);
th2.Start();
}
private void abc()
{
for (int i = 0; i < 20; i++)
{
mno(textBox1, "IndiaMART InterMESH LTD.");
}
}

private void xyz()
{
for (int i = 0; i < 20; i++)
{
mno(textBox2, "IndiaMART InterMESH LTD New");
}
}

private delegate void MyDelegate(TextBox t1, string S);
private void mno(TextBox t1, string S)
{
if (t1.InvokeRequired)
{
MyDelegate dd = new MyDelegate(mno);
t1.Invoke(dd, t1, S);
}
else
{
t1.Text += Environment.NewLine + S;
}
}
}
}

1 comment:

  1. Naween ji gud article for threading and client side java script Msg.
    Keep it up dude.

    ReplyDelete