Wednesday, March 28, 2012

How To Use Delegates In C# Easy Tutorial

While trying to access TextBox, RichTextBox etc you might encounter a error like


This error indicate that you cannot use TextBox or RichTextBox from any other tread except the default one.

To Access TextBox in your own thread you will need to use delegates for that.

Below is a simple code, in which I made 2 threads and 2 buttons (You will need to add 2 buttons in your project manually)

* DelegateWrite (Which write in the TextBox)
* DelegateRead (Which read from the TextBox)

Download .exe of this project from here (you will need Framework 4.0 installed)

1:  using System;  
2:  using System.Collections.Generic;  
3:  using System.ComponentModel;  
4:  using System.Data;  
5:  using System.Drawing;  
6:  using System.Linq;  
7:  using System.Text;  
8:  using System.Windows.Forms;  
9:  using System.Threading;  
10:  namespace Delegates  
11:  {  
12:    public partial class Form1 : Form  
13:    {  
14:      public Form1()  
15:      {  
16:        InitializeComponent();  
17:      }  
18:      void DelegateWrite()  
19:      {  
20:        if (textBox1.InvokeRequired)  
21:        {  
22:          textBox1.Invoke(new MethodInvoker(DelegateWrite));  
23:        }  
24:        else  
25:          textBox1.Text="String Generated from Delegate";  
26:      }  
27:      void DelegateRead()  
28:      {  
29:        if (textBox1.InvokeRequired)  
30:        {  
31:          textBox1.Invoke(new MethodInvoker(DelegateRead));  
32:        }  
33:        else  
34:          MessageBox.Show(textBox1.Text);  
35:      }  
36:      private void button1_Click(object sender, EventArgs e)  
37:      {  
38:        Thread objthread = new Thread(new ThreadStart(DelegateWrite));  
39:        objthread.Start();  
40:      }  
41:      private void button2_Click(object sender, EventArgs e)  
42:      {  
43:        Thread objthread = new Thread(new ThreadStart(DelegateRead));  
44:        objthread.Start();  
45:      }  
46:    }  
47:  }  

No comments:

Post a Comment