views:

447

answers:

4

Hi, Some time ago I have payed to a programmer for doing multithread server. In the meantime I have learned C# a bit and now I think I can see the slowndown problem - I was told by that guy that nothing is processed on the main thread (Form) so it cannot be frozen..but it is. But I think that altough BeginAcceptSocket is async operation, but its callback runs on the main thread and if there is locking, thats the reason why the app freezes. Am I right? Thanks

    this.mTcpListener.BeginAcceptSocket(this.AcceptClient, null);
  protected void AcceptClient(IAsyncResult ar)
        {
            //some locking stuff
        }
A: 

Anytime that your code gets a lock and then does something you have a candidate for a bottleneck, however, the thread that calls BeginAcceptSocket won't be blocked and can continue to do work until the callback event happens. It won't execute the callback handler until then so, in your example, none of the locking will occur until it has been contacted by a client. It still may be hanging up in the accept code if whatever it does at that point takes time or gets delayed due to communication issues, but it's hard to tell from your code sample if that's the case.

tvanfosson
Sorry, you misunderstood the question. I was asking whether I am right that AcceptClient method runs in the main thread, not asynch. So if there is lock, it will freeze the main app (Form).
Mirek
+1  A: 

I made small winapp test and the result is that even if 'AcceptClient' method is declared in the same class than this delegate is invoked from other thread than main winform app thread, and thus NO blocking is there.

psulek
+1  A: 

The Begin/End asynchronous IO methods use ThreadPool threads to execute the callback delegate, unless the operation can be completed instantly; in which case it executes synchronously on the calling thread.

From Calling Synchronous Methods Asynchronously:

Pass a delegate for a callback method to BeginInvoke. The method is executed on a ThreadPool thread when the asynchronous call completes. The callback method calls EndInvoke.

The callback should not often be occurring on the GUI thread. If the application window becomes unresponsive, it may be as a result of excessive invoking of methods on the GUI thread - usually to update controls.

Mark
A: 

AcceptClient(IAsyncResult ar) callback may be completed synchronously.

I guess if BeginAccept encounters that there is a new client it can execute callback method synchronously.

To be sure you have to stop your application under debugger when it froze and see what Main (event) thread is doing.

Generally it is better to have separate thread for doing any I/O.

Vadmyst