Help explain code with delegates
Im new to C# and the framework Im playing with and Im trying to figure out how some code works (there is nothing wrong with the code). Its a client/server application that sends some text from the client to the server and then receives and displays the same string in a textbox. The code below is from the client and its form. Only the stuff for receiving the string from the server is included here. I included some comments from the framework.
public class TestModuleMobile : PreCom.Core.ModuleBase, PreCom.Core.IForm
{
public delegate void ReceiveDelegate(string data);
public event ReceiveDelegate DataReceived;
public void Receive(byte[] data)
{
string text = Encoding.UTF8.GetString(data, 0, data.Length);
if (DataReceived != null)
DataReceived.Invoke(text);
}
public override bool Initialize()
{
PreCom.Application.Instance.Communication.Register(99, Receive);
// Register(uint receiverID, RecieveDelegate receiver): Called by modules to register for communication.
//
// Parameters:
// receiverID:
// Module Id
// receiver:
// The module receive function that will be called by the framework when data
// arrives to specific module. (This method should return as soon as possible
// to avoid timeouts)
_isInitialized = true;
return true;
}
}
public partial class TestModuleMobileForm : PreCom.Controls.PreComForm
{
TestModuleMobile _module;
开发者_JS百科public TestModuleMobileForm(TestModuleMobile module)
{
_module = module;
_module.DataReceived += new TestModuleMobile.ReceiveDelegate(DataReceived);
InitializeComponent();
}
void DataReceived(string data)
{
if (InvokeRequired)
{
ThreadStart myMethod = delegate { DataReceived(data); };
this.BeginInvoke(myMethod);
return;
}
listBox1.Items.Insert(0, data);
this.preComInput21.Text = "";
}
}
Questions:
1. public override bool Initialize() The function call to Register takes a ReceiveDelegate object as a second parameter. So how can I send a function to it (Receive) when its just a function? How does this work? 2. public void Receive(byte[] data) What happens in the if-case? How does invoke work? 3. void DataReceived(string data) What happens in the if-case (line by line)?There are many related posts here on Stackoverflow which you can browse through to get a better understanding of delegates. Once you have read through them, take a relook at your code and you will find it easier to understand.
Tip: Check to the right side of this web page to see all the related posts.
You need a full understading of delegates so you better start by reading these in order:
- Delegates (C# Programming Guide)
- Delegates Tutorial
- Delegates and Events in C# / .NET
精彩评论