I am very very new to delegates!
I have an AsyncCallback delegate which runs a method.
This method periodically writes text to the console (Console.WriteLine(“FooBar”))
This delegate is kicked off from my Main method and I need to find a way to keep this Main method open while the delegate runs. Otherwise, the program starts, kicks off the delegate and closes again so I am using Console.Readline.
Will this work? Will my program be able to both sit at Console.ReadLine while my delegate periodically writes text to the console with Console.WriteLine or am I an idiot? My code is below:
static void Main(string[] args)
{
NetworkStream myNetworkStream;
Socket socket;
IPEndPoint maxPort = new IPEndPoint(IPAddress.Parse("x.x.x.x"), xxxx);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
socket.Connect(maxPort);
myNetworkStream = new NetworkStream(socket);
byte[] buffer = new byte[1024];
int offset = 0;
int count = 1024;
string loginString = "FOOBARR";
ASCIIEncoding encoder = new ASCIIEncoding();
myNetworkStream.BeginRead(buffer, offset, count, new AsyncCallback(OnBeginRead), myNetworkStream);
myNetworkStream.Write(encoder.GetBytes(loginString), 0, encoder.GetByteCount(loginString));
Console.ReadLine();
}
public static void OnBeginRead(IAsyncResult ar)
{
NetworkStream ns = (NetworkStream)ar.AsyncState;
int bufferSize = 2014;
byte[] received = new byte[bufferSize];
string result = String.Empty;
ns.EndRead(ar);
int read;
while (true)
{
if (ns.DataAvailable)
{
read = ns.Read(received, 0, bufferSize);
result += Encoding.ASCII.GetString(received);
received = new byte[bufferSize];
Console.WriteLine(result);
}
else
{
Thread.Sleep(1000);
}
}
}
Also, if I call ‘myNetworkStream.BeginRead’ multiple times with different parameters, will a different version of my ‘OnBeginRead’ method start each time on a seperate thread on the processor or will the method that was running stop and be replaced by the more recent one?
Short answer: Yes
MSDN says this about calling BeginRead multiple times
Which implies that you shouldn’t call
BeginReadfrom multiple threads. This will lead to unexpected behaviour