473,466 Members | 1,631 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Locking and Async NetworkStream Operations

Hey all

While working with Async Methods and Networking I found something very
strange or better a bug?

To test it yourself create a new Windows Application with just a Button on
the Form.

Then modify the Code of the Form1 class until it looks like:

/****** BeginCode ******/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Net;

namespace WindowsApplication1 {
public partial class Form1 : Form {
TestClass c;
TcpClient cl;

public Form1() {
InitializeComponent();

Thread tr = new Thread(new ThreadStart(AcceptStuff));
tr.Start();

c = new TestClass();
}

public void AcceptStuff() {
TcpListener tcp = new TcpListener(IPAddress.Any, 1234);
tcp.Start();
cl = tcp.AcceptTcpClient();
}

private void button1_Click(object sender, EventArgs e) {
c.Add("bla");
}
}

class TestClass {
private object myLock = new object();
private MemoryStream m_memStream = new MemoryStream();
private NetworkStream m_netStream;

public TestClass() {
TcpClient tcp = new TcpClient("localhost", 1234);
m_netStream = tcp.GetStream();
}

public void Add(string bla) {
lock(myLock) {
Console.WriteLine("Lock1 locked");
byte[] buffer = Encoding.ASCII.GetBytes(bla);
m_netStream.BeginWrite(buffer, 0, buffer.Length, new
AsyncCallback(BeginWriteCallback), this);
Thread.Sleep(100);
Console.WriteLine("Lock1 unlocked");
}
}

private static void BeginWriteCallback(IAsyncResult ar) {
TestClass t = (TestClass)ar.AsyncState;
lock(t.myLock) {
Console.WriteLine("Lock2 locked");
t.m_netStream.EndWrite(ar);
Console.WriteLine("Lock2 unlocked");
}
}
}
}
/****** EndCode ******/
Now Point the Click-Event of your button to the Function:
button1_Click.

Now run the Application and Press the Button once.
You should see 4 Lines in your Debug View:
Lock1 locked
Lock1 unlocked
Lock2 locked
Lock2 unlocked

Looks good so far.

Now press the Button again and again and somewhen you'll see those 4 Lines:
Lock1 locked
Lock2 locked
Lock2 unlocked
Lock1 unlocked

Whao an already locked Object gets locked again?

Did I missunderstand something about the lock Statement? Or what's wrong
with it?
It's rather strange that this only occurs with the Async Method of a
NetworkStream, if I change it to a MemoryStream, it does never fail.

I guess this happens because the Async-Method is started from within the
Lock and when the Callback is fired, it somehow still thinks it's in that
locked Code-Part and doesn't try to lock again.
But it only happens sometimes and sometimes it does work (as you could test
yourself with the code above).

So anyone noticed something similiar? Is this a Bug in the Framework? Is
there any workaround?

Thanks for help

//Roman
Feb 15 '06 #1
4 1956
> Did I missunderstand something about the lock Statement? Or what's wrong
with it?
It's rather strange that this only occurs with the Async Method of a
NetworkStream, if I change it to a MemoryStream, it does never fail.

I guess this happens because the Async-Method is started from within the
Lock and when the Callback is fired, it somehow still thinks it's in that
locked Code-Part and doesn't try to lock again.
But it only happens sometimes and sometimes it does work (as you could
test
yourself with the code above).

So anyone noticed something similiar? Is this a Bug in the Framework? Is
there any workaround?


The situation you've described may happen when BeginWrite completes
synchronously ( it is not a bug ). This means that callback is executed from
within BeginWrite and in the same thread, that is why you reenter the lock
without blocking.

Why do you use locking here?
--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
Feb 15 '06 #2
Hi Roman,

Thanks for posting!

As Vadym mentioned, if the current thread is not very busy, it will execute
the Asynchronous method by itself. Actually, this issue is not happened
frequently. So this is not a bug issue.

In addition, if you want to execute these methods synchronously, I don't
understand why you will choose the asynchronous callback method? Could you
please give me more explanation about the current issue? Thanks for your
understanding!

Regards,

Yuan Ren [MSFT]
Microsoft Online Support

Feb 16 '06 #3
> The situation you've described may happen when BeginWrite completes
synchronously.


That single sentence cleared up so many things thanks!
Well in that example locking might not make sence.

About why I need a Lock:
Let's say we have a List somewhere in the TestClass and some functions to
access it, add elements or remove elements. And because a thread could add an
element while the Callback is working with the list, I need to "lock" the
List for synchronizing List access.
I know, blocking on a Callback is evil but I don't see much other
possibilities.
Feb 16 '06 #4
Hi Roman,

Thanks for your reply!

For the current issue, I suggest you use the synchronizing thread for the
current issue. The following article shows where we can get the "Wait
Synchronization Technology Sample":
http://msdn.microsoft.com/library/de...us/cpsamples/h
tml/wait_synchronization_technology_sample.asp

I hope this will be helpful!

Regards,

Yuan Ren [MSFT]
Microsoft Online Support

Feb 21 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Thomas Zöchling | last post by:
Hat jemand (schlechte) Erfahrungen mit Asynchronen NetworkStreams gemacht? In meiner Serveranwendung scheint die BeginRead Methode des NetworkStreams manchnmal den Stream nicht fertig zu lesen. ...
6
by: Shak | last post by:
Hi all, Three questions really: 1) The async call to the networkstream's endread() (or even endxxx() in general) blocks. Async calls are made on the threadpool - aren't we advised not to...
7
by: Shak | last post by:
Hi all, I'm trying to write a thread-safe async method to send a message of the form (type)(contents). My model is as follows: private void SendMessage(int type, string message) { //lets...
5
by: Arno | last post by:
reposted with the right microsoft managed newsgroup ID: Sorry for the inconvinience Hi, I've written a class for client-socket connection, but I get a lot of times the error message "Unable...
1
by: Rogier | last post by:
Hello, I'm Writing my own NZb download App, using Async Network Streams en Callback delegates. The Problem is that if I Want tot Receive Large chunks of data (for instance the LIST NEWSGROUPS...
10
by: Frankie | last post by:
It appears that System.Random would provide an acceptable means through which to generate a unique value used to identify multiple/concurrent asynchronous tasks. The usage of the value under...
3
by: Ryan Liu | last post by:
Will TcpClient.GetStream().Read()/ReadByte() block until at least one byte of data can be read? In a Client/Server application, what does it mean at the end of stream/no more data available? ...
3
by: Ryan Liu | last post by:
Hi, Is Async I/O (e.g. NetworkStream.Begin/End Read/Write) always better than synchronous I/O? At least as good? When I don't concern about easy or difficult to write code, should I always...
1
by: Ryan Liu | last post by:
Hi, I have a 100 clients/ one server application, use ugly one thread pre client approach. And both side user sync I/O. I frequently see the error on server side(client side code is same, but...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.