.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Delegate in C#.net

Posted By: Narayanan     Posted Date: February 16, 2012    Points: 2   Category :C#
Nice Article.

View Complete Post

More Related Resource Links

Basic Instincts: Implementing Callbacks with a Multicast Delegate


This month's column is a follow-up to the December 2002 installment in which I introduced the basic concepts and programming techniques associated with delegates. I am going to assume you have already read that column and that you are familiar with the fundamentals of programming delegates.

Ted Pattison

MSDN Magazine January 2003

asp.net c# DELEGATE THREAD: Multi threading



In my asp.net web application i have lengthy excution process like word merge. I want to merge the word documents and send to client in a procedure. Basically i am looking for run and forget kind of asynchronous process.

In my for loop i tried to create delegate and rstrat. like this

filenames is a string array, creating in the same loop and assiging values before calling delegate.


MailSender mail = new MailSender();



TestDelegate testdele = new

Protected Delegate Sub AsyncTaskDelegate()

 I am trying to get this to bind to a gridview, without any luck. I would like each asynctask to ultimately return seperate datasets, but for now I can deal with the same one being returned.<%@ Page Language="VB" AutoEventWireup="false" CodeFile="testAsynch.aspx.vb" Inherits="testAsynch" Async="true" AsyncTimeout="450" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script language="javascript" type="text/javascript"> function abortTask() { var obj = Sys.WebForms.PageRequestManager.getInstance(); if (obj.get_isInAsyncPostBack()) obj.abortPostBack(); } </script> <style type="text/css"> #UpdateProgress1 { width: 270px; background-color: #ffff99; height: 120px; top: 40%; left: 35%; position: absolute; border: solid 1px black; } #ProgressTemplate1 { font-size: 9pt; color: navy; font-family: verdana;

FAQ: How do I link a delegate to an event using Reflection?

How do I link a delegate to an event using Reflection?Please remember to mark the replies as answers if they help and unmark them if they provide no help. Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.

Converting C# codes with "Delegate function" to VB.Net

Can someone help me converting this code to VB.Net?/// <summary> /// Returns the binary data of the image in the specifed format. /// </summary> /// <param name="format">The format of the bitmap image specified as "gif", "jpg", "png", "bmp", "jxr" or "tiff".</param> public byte[] ToByteArray(string format) { //if image not altered return orig data if (_data != null) return _data; //placed in a thread set to STA to overcome 0xC0000005 thrown in encoder.Save if (!String.IsNullOrEmpty(Copyright)) { byte[] data = null; System.Threading.Thread worker = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(delegate (object obj) { BitmapEncoder encoder = GetEncoder(format); try { BitmapMetadata meta = new BitmapMetadata(format); meta.Copyright = Copyright; encoder.Frames.Insert(0, BitmapFrame.Create(_source, null, meta, null)); //using insert because we're getting error about IList not containing Add method using (MemoryStream memoryStream = new MemoryStream()) { encoder.Save(memoryStream);

Converting C# codes with "Delegate function" to VB.Net

Can someone help me converting this C sharp code to VB.Net? I tried to use several converters on google, none of them worked. /// <summary>     /// Returns the binary data of the image in the specifed format.     /// </summary>     /// <param name="format">The format of the bitmap image specified as "gif", "jpg", "png", "bmp", "jxr" or "tiff".</param>     public byte[] ToByteArray(string format)     {         //if image not altered return orig data         if (_data != null)             return _data;         //placed in a thread set to STA to overcome 0xC0000005 thrown in encoder.Save         if (!String.IsNullOrEmpty(Copyright))         {             byte[] data = null;             System.Threading.Thread worker = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(delegate (object obj) {                 BitmapEncoder encoder = GetEncoder(format);                 try &

What is the use of delegate


I have studied lots of books and materials on internet but I can never understand what is the use of delegate in development. Actually I want to know in what particular situation a developer should use delegate in code. Please provide me some example.

C#NET2008 FrmMain using DELEGATE CLASS Method



Hullo Good Guys,


I am back here seeking help. Please Help me.


Here us the description of what I was ihstructed to do by the System Analyst.


Create DELEGATE Class to perform Mortgage computation and return the result back to the calling FrmMortgage.cs. Apparently my coding are not working as I am not familiar with DELEGATE Class


Here are the Erro

How Do I maintain the chronological order in which Asynchronous delegate calls are made?


I have created a basic logging framework for my application that writes log messages to a local text file using an Asynchronous delegate.

My application has many threads running however, and as a result, the order of the log entries in the text file is not chronological.

So I have two competing requirements: on one hand, my WriteToLog() method has to return almost immediately so that it doesn't block in-flight code, while at the same time the log file has to be in chronological order.

Any ideas?  Some of the problems I've encountered are:

1a.  Trying to use a Queue (with a lock{ } around it) to maintain the order seems to result in deadlocks

1b.  Even if I use a Queue, at some point the Queue must be written to disk, so it seems like I'd have to frequently have WriteToLog spin off a "WriteToDisk" like method.

2a.  I've considered instantiating a new thread which polls the Queue from (1a) and writes to disk in a loop, say, every 5 seconds.  I'm leaning more towards this method.

3.  I've looked into log4net and some other stuff but it just seems like overkill, and I'd really like to have my own framework for this seemingly simple task.



Delegate issue


Got a user control that has a Listbox on it and I want to be able to pass the selected value back to the main page. 

User Control code:

using System;
using System.Web.UI;

public delegate void SendData(string data);

public partial class _controls_Filter_Staff : UserControl{
    public event SendData mSendData;

    protected void Page_Load(object sender, EventArgs e){

    protected void selStaffList_OnSelectedIndexChanged(object sender, EventArgs e){
        if (Convert.ToInt32(selStaffList.SelectedValue) >= 0 && mSendData != null){

Main page that has the user control:

    protected void Page_Load(object sender, EventArgs e){

        ucFilterStaff.mSendData += GetSelectedStaff; /* ERROR HERE Line 11 */


    private void GetSelectedStaff(string value){
        TextBox txtUserList = (TextBox) fvMain.FindControl("txtUserList");
        if (txtUserList == null) return;

        txtUserList.Text += value + ";";

This is the error I get back and I've tried everything I know, but cannot sort it.  Probably something stupid but I just cannot see it.

System.Web.HttpUnhandledException: Exce

SPSecurity.RunWithElevatedPrivileges(delegate(myCode){}); to add file to documentlibrary


I got a document library on which BreakRoleInheritance(false) was executed. I got a test-user which is allowed to view but not add or edit items. Nobody has rights to add an item. But now I got some custom code executed by the test-user which should allow him to add a new file to a documentlibrary.

SPFile newFile;

                        newFile = docLib.RootFolder.Files.Add(
                          fileUrl, fileStream);
Even with elevated privileges the user gets in this line of code a "access denied" message. I'm guessing I'm trying to use the wrong approach so any help is appreciated.

Delegate Control not working


I have a question about delegate controls. I am trying to replace the search box. I have done the following - 

  1. Created a empty SP 2010 project with a control class. 
  2. Added a feature and elements.xml to the same project
  3. Deployed the feature and activated it (I can see it in my site list of features)
But my search box still appears to be the default one...what am I doing wrong?

My elements.xml is as follows - 
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    ControlAssembly="DelegateControl001Feature, Version=, Culture=neutral, PublicKeyToken=69948fee36b953cf"/>

And my ascx file just has a asp:TextBox with custom text in it.

I am assuming that no master file changes are necessary right?

C# delegate Exception


  I am stuck with an InvalidCast Exception. I am calling a delegate to run some function. In the callback method of the delegate I am trying to get the return value of the function as shown below.

         public delegate SyncHelper.SyncPlan RunJobDelegate();

         public static void SyncJobCallback(IAsyncResult result)

            RunJobDelegate runSyncJob = (RunJobDelegate)result.AsyncState;
            SyncHelper.SyncPlan obj_Plan = runSyncJob.EndInvoke(result);

When RunJobDelegate runSyncJob = (RunJobDelegate)result.AsyncState; is called I am hitting an exception saying "Unable to cast object of type 'RunJobDelegate' to type 'RunJobDelegate'. "

System.InvalidCastException was unhandled
  Message=Unable to cast object of type 'RunJobDelegate' to type 'RunJobDelegate'.
       at WizardSync_v2.Forms.MainForm.SyncJobCallback(IAsyncResult res

why we go for delegate?



        by using delegate we can call the method.why we go for delegate?.by creating the instance we can call the methd.

what is the main purpose of delegate?

plz reply as soon as possible.

SharePoint Search Delegate Control


Any ideas why the search delegate control <SharePoint:DelegateControl runat="server" ControlId="SmallSearchInputBox"/> would not render anything on my portal? Actually, when I looked at the page source, I saw that delegate control did infact render the html however it was enclosed in <div id="SearchArea" style="display:none"></div> so it is hidden.

Thanks for your help

Get delegate arguments inside delegate


Hi all,

Could someone please help me to understand how to get all parameters passed to delegate inside delegate itself?

I have class :

    public class ShopManager : ShopEntities
            public ShopManager getWhere(Func<Object, Object> dataList)
                var x = dataList.???; // how to get arguments?
                return this;
            public Object getLike(Object dataValue)
                return dataValue;

Then i call it as :

    ShopManager shopManager = new ShopManager()
    var demo = shopManager.getWhere(xxx => shopManager.getLike("DATA"));

The question is : **how to get passed parameters "xxx" and "DATA" inside method getWhere()?**

Thanks in advance.

Delegate controls in SharePoint 2010


Hi there,

I am working on some SS2010 Page layouts and I want to display quick launch ( left hand "Local Site Only"  Navigation) in some layouts ( NOT IN ALL layouts). I am thinking of using Delegate controls, but since for quick launch SS2010 OOTB has lot of codes, I am not sure how to use, can you please let me know the right way!




ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend