473,569 Members | 2,692 Online
Bytes | Software Development & Data Engineering Community
+ 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.Collecti ons.Generic;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows. Forms;
using System.IO;
using System.Net.Sock ets;
using System.Threadin g;
using System.Net;

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

public Form1() {
InitializeCompo nent();

Thread tr = new Thread(new ThreadStart(Acc eptStuff));
tr.Start();

c = new TestClass();
}

public void AcceptStuff() {
TcpListener tcp = new TcpListener(IPA ddress.Any, 1234);
tcp.Start();
cl = tcp.AcceptTcpCl ient();
}

private void button1_Click(o bject 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("loca lhost", 1234);
m_netStream = tcp.GetStream() ;
}

public void Add(string bla) {
lock(myLock) {
Console.WriteLi ne("Lock1 locked");
byte[] buffer = Encoding.ASCII. GetBytes(bla);
m_netStream.Beg inWrite(buffer, 0, buffer.Length, new
AsyncCallback(B eginWriteCallba ck), this);
Thread.Sleep(10 0);
Console.WriteLi ne("Lock1 unlocked");
}
}

private static void BeginWriteCallb ack(IAsyncResul t ar) {
TestClass t = (TestClass)ar.A syncState;
lock(t.myLock) {
Console.WriteLi ne("Lock2 locked");
t.m_netStream.E ndWrite(ar);
Console.WriteLi ne("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 1964
> 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_synchroniz ation_technolog y_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
3100
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. ... socket = socketForClient; buffer = new byte; networkStream = new NetworkStream(socketForClient); callbackRead = new...
6
3807
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 cause these to block? 2) You can connect together a binaryreader to a networkstream:
7
2848
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 send the messagetype via async NetworkStream ns = client.GetStream(); //assume client globally accessible
5
15704
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 to read data from the transport connection" when restart reading the stream with socket.BeginRead in the Sub SocketIncomingMsg. I'm debugging now for...
1
2466
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 Response). I do not get the Data at once. Here is a piece of my source code: I call the NetworkStream.ReadBegin as follows:
10
4488
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 consideration here is that it is supplied to the AsyncOperationManager.CreateOperation(userSuppliedState) method... with userSuppliedState being, more...
3
2679
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? Client could send data once few seconds of minutes. Is there an "end" at all? In a C/S application, if server side call BeginginRead() again in...
3
3568
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 use Async I/O?
1
20581
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 I don't see the error): "System.IO.IOException: Unable to read data from the transport connection:A blocking operation was interrupted by a call...
0
7698
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7612
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7673
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5513
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5219
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3640
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2113
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 we have to send another system
0
937
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.