Author: alanmc
Date: 2007-04-01 16:35:23 -0400 (Sun, 01 Apr 2007)
New Revision: 75271

Modified:
   trunk/bitsharp/src/MonoTorrent.Client/Managers/ConnectionManager.cs
   trunk/bitsharp/src/MonoTorrent.Client/Managers/TorrentManager.cs
   trunk/bitsharp/src/MonoTorrent.Client/PeerMessages/UnchokeMessage.cs
   trunk/bitsharp/src/MonoTorrent.Client/Peers/Peer.cs
Log:
First part of a refactor to reduce the number of threads created by the library.

Modified: trunk/bitsharp/src/MonoTorrent.Client/Managers/ConnectionManager.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent.Client/Managers/ConnectionManager.cs 
2007-04-01 20:20:59 UTC (rev 75270)
+++ trunk/bitsharp/src/MonoTorrent.Client/Managers/ConnectionManager.cs 
2007-04-01 20:35:23 UTC (rev 75271)
@@ -87,7 +87,11 @@
 
         private List<TorrentManager> torrents;
 
-
+        internal MessageHandler MessageHandler
+        {
+            get { return this.messageHandler; }
+        }
+        private MessageHandler messageHandler;
         /// <summary>
         /// The number of half open connections
         /// </summary>
@@ -151,6 +155,7 @@
             this.onEncryptorReadyHandler = new 
EncryptorReadyHandler(onEncryptorReady);
             this.onEncryptorIOErrorHandler = new 
EncryptorIOErrorHandler(onEncryptorError);
             this.onEncryptorEncryptionErrorHandler = new 
EncryptorEncryptionErrorHandler(onEncryptorError);
+            this.messageHandler = new MessageHandler();
         }
 
         #endregion
@@ -182,6 +187,7 @@
 
                 id.Peer.Connection = new TCPConnection(id.Peer.Location, 
id.TorrentManager.Torrent.Pieces.Count, encryptor);
                 id.Peer.Connection.ProcessingQueue = true;
+                id.Peer.LastConnectionAttempt = DateTime.Now;
                 id.Peer.Connection.LastMessageSent = DateTime.Now;
                 id.Peer.Connection.LastMessageReceived = DateTime.Now;
                 
id.Peer.Connection.BeginConnect(this.endCreateConnectionCallback, id);
@@ -323,18 +329,16 @@
 
         private void onPeerHandshakeSent(PeerConnectionID id)
         {
-            lock (id.TorrentManager.listLock)
+            lock (id.TorrentManager.resumeLock)
+            lock (id)
             {
-                lock (id)
-                {
-                    Logger.Log(id, "Sent Handshake");
-                    Logger.Log(id, "Recieving handshake");
+                Logger.Log(id, "Sent Handshake");
+                Logger.Log(id, "Recieving handshake");
 
-                    // Receive the handshake
-                    // FIXME: Will fail if protocol version changes. FIX THIS
-                    ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.sendBuffer);
-                    ReceiveMessage(id, 68, this.handshakeReceievedCallback);
-                }
+                // Receive the handshake
+                // FIXME: Will fail if protocol version changes. FIX THIS
+                ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.sendBuffer);
+                ReceiveMessage(id, 68, this.handshakeReceievedCallback);
             }
         }
 
@@ -351,41 +355,39 @@
 
             try
             {
-                lock (id.TorrentManager.listLock)
+                lock (id.TorrentManager.resumeLock)
+                lock (id)
                 {
-                    lock (id)
-                    {
-                        // If the connection is closed, just return
-                        if (id.Peer.Connection == null)
-                            return;
+                    // If the connection is closed, just return
+                    if (id.Peer.Connection == null)
+                        return;
 
-                        // Decode the handshake and handle it
-                        msg = new HandshakeMessage();
-                        msg.Decode(id.Peer.Connection.recieveBuffer, 0, 
id.Peer.Connection.BytesToRecieve);
-                        msg.Handle(id);
+                    // Decode the handshake and handle it
+                    msg = new HandshakeMessage();
+                    msg.Decode(id.Peer.Connection.recieveBuffer, 0, 
id.Peer.Connection.BytesToRecieve);
+                    msg.Handle(id);
 
-                        Logger.Log(id, "Handshake recieved");
-                        HandshakeMessage handshake = msg as HandshakeMessage;
+                    Logger.Log(id, "Handshake recieved");
+                    HandshakeMessage handshake = msg as HandshakeMessage;
 
-                        if (id.Peer.Connection.SupportsFastPeer && 
ClientEngine.SupportsFastPeer)
-                        {
-                            if (id.TorrentManager.Bitfield.AllFalse)
-                                msg = new HaveNoneMessage();
+                    if (id.Peer.Connection.SupportsFastPeer && 
ClientEngine.SupportsFastPeer)
+                    {
+                        if (id.TorrentManager.Bitfield.AllFalse)
+                            msg = new HaveNoneMessage();
 
-                            else if (id.TorrentManager.Bitfield.AllTrue)
-                                msg = new HaveAllMessage();
+                        else if (id.TorrentManager.Bitfield.AllTrue)
+                            msg = new HaveAllMessage();
 
-                            else
-                                msg = new 
BitfieldMessage(id.TorrentManager.Bitfield);
-                        }
                         else
-                        {
                             msg = new 
BitfieldMessage(id.TorrentManager.Bitfield);
-                        }
-
-                        ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.recieveBuffer);
-                        SendMessage(id, msg, this.bitfieldSentCallback);
                     }
+                    else
+                    {
+                        msg = new BitfieldMessage(id.TorrentManager.Bitfield);
+                    }
+
+                    ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.recieveBuffer);
+                    SendMessage(id, msg, this.bitfieldSentCallback);
                 }
             }
             catch (TorrentException ex)
@@ -408,27 +410,25 @@
         /// <param name="result"></param>
         private void OnPeerBitfieldSent(PeerConnectionID id)
         {
-            lock (id.TorrentManager.listLock)
+            lock (id.TorrentManager.resumeLock)
+            lock (id)
             {
-                lock (id)
-                {
-                    if (id.Peer.Connection == null)
-                        return;
+                if (id.Peer.Connection == null)
+                    return;
 
-                    // Free the old buffer and get a new one to recieve the 
length of the next message
-                    ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.sendBuffer);
+                // Free the old buffer and get a new one to recieve the length 
of the next message
+                ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.sendBuffer);
 
-                    // Now we will enqueue a FastPiece message for each piece 
we will allow the peer to download
-                    // even if they are choked
-                    if (ClientEngine.SupportsFastPeer && 
id.Peer.Connection.SupportsFastPeer)
-                        for (int i = 0; i < 
id.Peer.Connection.AmAllowedFastPieces.Count; i++)
-                            id.Peer.Connection.EnQueue(new 
AllowedFastMessage(id.Peer.Connection.AmAllowedFastPieces[i]));
+                // Now we will enqueue a FastPiece message for each piece we 
will allow the peer to download
+                // even if they are choked
+                if (ClientEngine.SupportsFastPeer && 
id.Peer.Connection.SupportsFastPeer)
+                    for (int i = 0; i < 
id.Peer.Connection.AmAllowedFastPieces.Count; i++)
+                        id.Peer.Connection.EnQueue(new 
AllowedFastMessage(id.Peer.Connection.AmAllowedFastPieces[i]));
 
-                    // Allow the auto processing of the send queue to commence
-                    id.Peer.Connection.ProcessingQueue = false;
+                // Allow the auto processing of the send queue to commence
+                id.Peer.Connection.ProcessingQueue = false;
 
-                    ReceiveMessage(id, 4, this.messageLengthReceivedCallback);
-                }
+                ReceiveMessage(id, 4, this.messageLengthReceivedCallback);
             }
         }
 
@@ -439,38 +439,36 @@
         /// <param name="result"></param>
         private void onPeerMessageLengthReceived(PeerConnectionID id)
         {
-            lock (id.TorrentManager.listLock)
+            lock (id.TorrentManager.resumeLock)
+            lock (id)
             {
-                lock (id)
-                {
-                    // If the connection is null, we just return
-                    if (id.Peer.Connection == null)
-                        return;
+                // If the connection is null, we just return
+                if (id.Peer.Connection == null)
+                    return;
 
-                    Logger.Log(id, "Recieved message length");
+                Logger.Log(id, "Recieved message length");
 
-                    // Decode the message length from the buffer. It is a big 
endian integer, so make sure
-                    // it is converted to host endianness.
-                    int messageBodyLength = 
IPAddress.NetworkToHostOrder(BitConverter.ToInt32(id.Peer.Connection.recieveBuffer,
 0));
+                // Decode the message length from the buffer. It is a big 
endian integer, so make sure
+                // it is converted to host endianness.
+                int messageBodyLength = 
IPAddress.NetworkToHostOrder(BitConverter.ToInt32(id.Peer.Connection.recieveBuffer,
 0));
 
-                    // Free the existing receive buffer and then get a new one 
which can
-                    // contain the amount of bytes we need to receive.
-                    ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.recieveBuffer);
+                // Free the existing receive buffer and then get a new one 
which can
+                // contain the amount of bytes we need to receive.
+                ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.recieveBuffer);
 
-                    // If bytes to receive is zero, it means we received a 
keep alive message
-                    // so we just start receiving a new message length again
-                    if (messageBodyLength == 0)
-                    {
-                        id.Peer.Connection.LastMessageReceived = DateTime.Now;
-                        ReceiveMessage(id, 4, 
this.messageLengthReceivedCallback);
-                    }
+                // If bytes to receive is zero, it means we received a keep 
alive message
+                // so we just start receiving a new message length again
+                if (messageBodyLength == 0)
+                {
+                    id.Peer.Connection.LastMessageReceived = DateTime.Now;
+                    ReceiveMessage(id, 4, this.messageLengthReceivedCallback);
+                }
 
-                    // Otherwise queue the peer in the Receive buffer and try 
to resume downloading off him
-                    else
-                    {
-                        Logger.Log(id, "Recieving message");
-                        ReceiveMessage(id, messageBodyLength, 
this.messageReceivedCallback);
-                    }
+                // Otherwise queue the peer in the Receive buffer and try to 
resume downloading off him
+                else
+                {
+                    Logger.Log(id, "Recieving message");
+                    ReceiveMessage(id, messageBodyLength, 
this.messageReceivedCallback);
                 }
             }
         }
@@ -488,44 +486,39 @@
 
             try
             {
-                lock (id.TorrentManager.listLock)
+                lock (id.TorrentManager.resumeLock)
+                lock (id)
                 {
-                    lock (id)
-                    {
-                        if (id.Peer.Connection == null)
-                            return;
+                    if (id.Peer.Connection == null)
+                        return;
 
-                        // Attempt to decode the message from the buffer.
-                        message = 
PeerwireEncoder.Decode(id.Peer.Connection.recieveBuffer, 0, 
id.Peer.Connection.BytesToRecieve, id.TorrentManager);
-                        message.Handle(id);
-                        Logger.Log(id, "Recieved message: " + 
message.GetType().Name);
+                    // Attempt to decode the message from the buffer.
+                    //message = 
PeerwireEncoder.Decode(id.Peer.Connection.recieveBuffer, 0, 
id.Peer.Connection.BytesToRecieve, id.TorrentManager);
+                    //message.Handle(id);
+                    this.messageHandler.EnqueueReceived(id, 
id.Peer.Connection.recieveBuffer, 0, id.Peer.Connection.BytesToRecieve);
+                    Logger.Log(id, "Recieved message: " + 
message.GetType().Name);
 
 
-                        // Fire the event to say we recieved a new message
-                        if (this.PeerMessageTransferred != null)
-                            this.PeerMessageTransferred(id, new 
PeerMessageEventArgs((IPeerMessage)message, Direction.Incoming));
+                    // if the peer has sent us three bad pieces, we close the 
connection.
+                    if (id.Peer.HashFails == 3)
+                    {
+                        reason = "3 hashfails";
+                        Logger.Log(id, "3 hashfails");
+                        cleanUp = true;
+                        return;
+                    }
 
+                    id.Peer.Connection.LastMessageReceived = DateTime.Now;
 
-                        // if the peer has sent us three bad pieces, we close 
the connection.
-                        if (id.Peer.HashFails == 3)
-                        {
-                            reason = "3 hashfails";
-                            Logger.Log(id, "3 hashfails");
-                            cleanUp = true;
-                            return;
-                        }
+                    // Free the large buffer used to recieve the piece message 
and get a small buffer
+                    ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.recieveBuffer);
 
-                        id.Peer.Connection.LastMessageReceived = DateTime.Now;
-
-                        // Free the large buffer used to recieve the piece 
message and get a small buffer
-                        ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.recieveBuffer);
-
-                        ReceiveMessage(id, 4, 
this.messageLengthReceivedCallback);
-                    }
+                    ReceiveMessage(id, 4, this.messageLengthReceivedCallback);
                 }
             }
             catch (TorrentException ex)
             {
+                reason = ex.Message;
                 Logger.Log(id, "Invalid message recieved: " + ex.Message);
                 cleanUp = true;
                 return;
@@ -544,23 +537,21 @@
         /// <param name="result"></param>
         private void onPeerMessageSent(PeerConnectionID id)
         {
-            lock (id.TorrentManager.listLock)
+            lock (id.TorrentManager.resumeLock)
+            lock (id)
             {
-                lock (id)
-                {
-                    // If the peer has been cleaned up, just return.
-                    if (id.Peer.Connection == null)
-                        return;
+                // If the peer has been cleaned up, just return.
+                if (id.Peer.Connection == null)
+                    return;
 
-                    // Fire the event to let the user know a message was sent
-                    if (this.PeerMessageTransferred != null)
-                        this.PeerMessageTransferred(id, new 
PeerMessageEventArgs((IPeerMessage)id.Peer.Connection.CurrentlySendingMessage, 
Direction.Outgoing));
+                // Fire the event to let the user know a message was sent
+                if (this.PeerMessageTransferred != null)
+                    this.PeerMessageTransferred(id, new 
PeerMessageEventArgs((IPeerMessage)id.Peer.Connection.CurrentlySendingMessage, 
Direction.Outgoing));
 
-                    ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.sendBuffer);
-                    Logger.Log(id, "Sent message: " + 
id.Peer.Connection.CurrentlySendingMessage.ToString());
-                    id.Peer.Connection.LastMessageSent = DateTime.Now;
-                    this.ProcessQueue(id);
-                }
+                ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.sendBuffer);
+                Logger.Log(id, "Sent message: " + 
id.Peer.Connection.CurrentlySendingMessage.ToString());
+                id.Peer.Connection.LastMessageSent = DateTime.Now;
+                this.ProcessQueue(id);
             }
         }
 
@@ -574,7 +565,7 @@
         {
             try
             {
-                lock (id.TorrentManager.listLock)
+                lock (id.TorrentManager.resumeLock)
                     lock (id)
                     {
                         if (id.Peer.Connection == null)
@@ -589,7 +580,6 @@
                         id.TorrentManager.Peers.Enqueue(id, 
PeerType.DownloadQueue);
                         id.TorrentManager.ResumePeers();
                     }
-
             }
             catch (SocketException)
             {
@@ -610,7 +600,7 @@
 
             try
             {
-                lock (id.TorrentManager.listLock)
+                lock (id.TorrentManager.resumeLock)
                     lock (id)
                     {
                         if (id.Peer.Connection == null)
@@ -672,7 +662,7 @@
 
             try
             {
-                lock (id.TorrentManager.listLock)
+                lock (id.TorrentManager.resumeLock)
                     lock (id)
                     {
                         // If the connection is null, just return
@@ -739,7 +729,7 @@
 
             try
             {
-                lock (id.TorrentManager.listLock)
+                lock (id.TorrentManager.resumeLock)
                     lock (id)
                     {
                         // If the peer has disconnected, don't continue
@@ -811,80 +801,7 @@
 
         internal void CleanupSocket(PeerConnectionID id, bool localClose, 
string message)
         {
-            if (id == null) // Sometimes onEncryptoError will fire with a null 
id
-                return;
-
-            try
-            {
-                lock (id.TorrentManager.listLock)
-                {
-                    lock (id)
-                    {
-                        Logger.Log(id, "Cleanup Reason : " + message);
-                        Logger.FlushToDisk(id);
-
-                        // We can't clean up until the pending sends and 
receives have all had the corresponding End*** method called
-                        if (!localClose && (id.Peer.ActiveReceive || 
id.Peer.ActiveSend))
-                            return;
-
-                        Logger.Log(id, "*******Cleaning up*******");
-                        System.Threading.Interlocked.Decrement(ref 
this.openConnections);
-                        id.TorrentManager.PieceManager.RemoveRequests(id);
-                        id.Peer.CleanedUpCount++;
-                        id.Peer.ActiveReceive = false;
-                        id.Peer.ActiveSend = false;
-
-                        if (id.Peer.Connection != null)
-                        {
-                            if (this.PeerDisconnected != null)
-                                this.PeerDisconnected(null, new 
PeerConnectionEventArgs(id, Direction.None));
-
-                            ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.sendBuffer);
-                            ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.recieveBuffer);
-
-                            if (!id.Peer.Connection.AmChoking)
-                                id.TorrentManager.UploadingTo--;
-
-                            id.Peer.Connection.Dispose();
-                            id.Peer.Connection = null;
-                        }
-                        else
-                        {
-                            Logger.Log(id, "!!!!Connection already null!!!!");
-                        }
-
-                        int found = 0;
-                        if 
(id.TorrentManager.Peers.ConnectedPeers.Contains(id))
-                            found++;
-                        if 
(id.TorrentManager.Peers.ConnectingToPeers.Contains(id))
-                            found++;
-                        if 
(id.TorrentManager.Peers.AvailablePeers.Contains(id))
-                            found++;
-
-                        if (found > 1)
-                        {
-                            Logger.Log("Found: " + found.ToString());
-                        }
-
-                        id.TorrentManager.Peers.RemovePeer(id, 
PeerType.UploadQueue);
-                        id.TorrentManager.Peers.RemovePeer(id, 
PeerType.DownloadQueue);
-
-                        if 
(id.TorrentManager.Peers.ConnectedPeers.Contains(id))
-                            id.TorrentManager.Peers.RemovePeer(id, 
PeerType.Connected);
-
-                        if 
(id.TorrentManager.Peers.ConnectingToPeers.Contains(id))
-                            id.TorrentManager.Peers.RemovePeer(id, 
PeerType.Connecting);
-
-                        if (id.Peer.PeerId != ClientEngine.PeerId)
-                            if 
(!id.TorrentManager.Peers.AvailablePeers.Contains(id) && id.Peer.CleanedUpCount 
< 5)
-                                id.TorrentManager.Peers.AddPeer(id, 
PeerType.Available);
-                    }
-                }
-            }
-            finally
-            {
-                TryConnect();
-            }
+            this.messageHandler.EnqueueCleanup(id);
         }
 
 
@@ -946,12 +863,12 @@
                         if (this.PeerConnected != null)
                             this.PeerConnected(null, new 
PeerConnectionEventArgs(id, Direction.Incoming));
 
-                                               if ((this.openConnections >= 
this.MaxOpenConnections))
-                                               {
-                                                       reason = "Too many 
peers";
-                                                       cleanUp = true;
-                                                       return;
-                                               }
+                        if ((this.openConnections >= this.MaxOpenConnections))
+                        {
+                            reason = "Too many peers";
+                            cleanUp = true;
+                            return;
+                        }
                         Logger.Log(id, "Recieving message length");
                         ClientEngine.ConnectionManager.ReceiveMessage(id, 4, 
this.messageLengthReceivedCallback);
                     }
@@ -1007,6 +924,9 @@
         {
             lock (this.torrents)
             {
+                if (!this.messageHandler.IsActive)
+                    this.messageHandler.Start();
+
                 if (this.torrents.Contains(torrentManager))
                     throw new TorrentException("TorrentManager is already 
registered in the connection manager");
 
@@ -1094,7 +1014,8 @@
                             if ((manager.State != TorrentState.Seeding ||
                                (manager.State == TorrentState.Seeding && 
!manager.Peers.AvailablePeers[i].Peer.IsSeeder))
                                 && 
(!manager.Peers.AvailablePeers[i].Peer.ActiveReceive)
-                                && 
(!manager.Peers.AvailablePeers[i].Peer.ActiveSend))
+                                && 
(!manager.Peers.AvailablePeers[i].Peer.ActiveSend)
+                                && 
manager.Peers.AvailablePeers[i].Peer.LastConnectionAttempt < 
DateTime.Now.AddMinutes(-1))
                                 break;
 
                         // If this is true, there were no peers in the 
available list to connect to.
@@ -1181,10 +1102,88 @@
             }
             catch (NullReferenceException)
             {
-                CleanupSocket(id,"Null ref encryptor error");
+                CleanupSocket(id, "Null ref encryptor error");
             }
         }
 
         #endregion
+
+        internal void AsyncCleanupSocket(PeerConnectionID id, bool localClose, 
string message)
+        {
+            if (id == null) // Sometimes onEncryptoError will fire with a null 
id
+                return;
+
+            try
+            {
+                lock (id.TorrentManager.listLock)
+                {
+                    lock (id)
+                    {
+                        Logger.Log(id, "Cleanup Reason : " + message);
+                        Logger.FlushToDisk(id);
+
+                        // We can't clean up until the pending sends and 
receives have all had the corresponding End*** method called
+                        if (!localClose && (id.Peer.ActiveReceive || 
id.Peer.ActiveSend))
+                            return;
+
+                        Logger.Log(id, "*******Cleaning up*******");
+                        System.Threading.Interlocked.Decrement(ref 
this.openConnections);
+                        id.TorrentManager.PieceManager.RemoveRequests(id);
+                        id.Peer.CleanedUpCount++;
+                        id.Peer.ActiveReceive = false;
+                        id.Peer.ActiveSend = false;
+
+                        if (id.Peer.Connection != null)
+                        {
+                            if (this.PeerDisconnected != null)
+                                this.PeerDisconnected(null, new 
PeerConnectionEventArgs(id, Direction.None));
+
+                            ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.sendBuffer);
+                            ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.recieveBuffer);
+
+                            if (!id.Peer.Connection.AmChoking)
+                                id.TorrentManager.UploadingTo--;
+
+                            id.Peer.Connection.Dispose();
+                            id.Peer.Connection = null;
+                        }
+                        else
+                        {
+                            Logger.Log(id, "!!!!Connection already null!!!!");
+                        }
+
+                        int found = 0;
+                        if 
(id.TorrentManager.Peers.ConnectedPeers.Contains(id))
+                            found++;
+                        if 
(id.TorrentManager.Peers.ConnectingToPeers.Contains(id))
+                            found++;
+                        if 
(id.TorrentManager.Peers.AvailablePeers.Contains(id))
+                            found++;
+
+                        if (found > 1)
+                        {
+                            Logger.Log("Found: " + found.ToString());
+                        }
+
+                        id.TorrentManager.Peers.RemovePeer(id, 
PeerType.UploadQueue);
+                        id.TorrentManager.Peers.RemovePeer(id, 
PeerType.DownloadQueue);
+
+                        if 
(id.TorrentManager.Peers.ConnectedPeers.Contains(id))
+                            id.TorrentManager.Peers.RemovePeer(id, 
PeerType.Connected);
+
+                        if 
(id.TorrentManager.Peers.ConnectingToPeers.Contains(id))
+                            id.TorrentManager.Peers.RemovePeer(id, 
PeerType.Connecting);
+
+                        if (id.Peer.PeerId != ClientEngine.PeerId)
+                            if 
(!id.TorrentManager.Peers.AvailablePeers.Contains(id) && id.Peer.CleanedUpCount 
< 5)
+                                id.TorrentManager.Peers.AddPeer(id, 
PeerType.Available);
+                    }
+                }
+            }
+            finally
+            {
+                TryConnect();
+            }
+        }
     }
 }

Modified: trunk/bitsharp/src/MonoTorrent.Client/Managers/TorrentManager.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent.Client/Managers/TorrentManager.cs    
2007-04-01 20:20:59 UTC (rev 75270)
+++ trunk/bitsharp/src/MonoTorrent.Client/Managers/TorrentManager.cs    
2007-04-01 20:35:23 UTC (rev 75271)
@@ -47,6 +47,7 @@
     /// </summary>
     public class TorrentManager : IDisposable, IEquatable<TorrentManager>
     {
+        internal readonly object resumeLock = new object();
         internal Queue<int> finishedPieces = new Queue<int>();
         #region Events
         /// <summary>
@@ -254,6 +255,7 @@
             if (this.state == TorrentState.Paused)
             {
                 UpdateState(TorrentState.Downloading);
+                lock (this.resumeLock)
                 this.ResumePeers();
                 return;
             }
@@ -289,9 +291,9 @@
                 this.loadedFastResume = false;
             }
 
-                       this.TrackerManager.Scrape();
-                       this.trackerManager.Announce(TorrentEvent.Started); // 
Tell server we're starting
-                       ClientEngine.ConnectionManager.RegisterManager(this);
+            this.TrackerManager.Scrape();
+            this.trackerManager.Announce(TorrentEvent.Started); // Tell server 
we're starting
+            ClientEngine.ConnectionManager.RegisterManager(this);
 
             if (this.Progress == 100.0)
                 UpdateState(TorrentState.Seeding);
@@ -315,11 +317,11 @@
             {
                 while (this.peers.ConnectingToPeers.Count > 0)
                     lock (this.peers.ConnectingToPeers[0])
-                        
ClientEngine.ConnectionManager.CleanupSocket(this.peers.ConnectingToPeers[0], 
true, "Called stop");
+                        
ClientEngine.ConnectionManager.AsyncCleanupSocket(this.peers.ConnectingToPeers[0],
 true, "Called stop");
 
                 while (this.peers.ConnectedPeers.Count > 0)
                     lock (this.peers.ConnectedPeers[0])
-                        
ClientEngine.ConnectionManager.CleanupSocket(this.peers.ConnectedPeers[0], 
true, "Called stop");
+                        
ClientEngine.ConnectionManager.AsyncCleanupSocket(this.peers.ConnectedPeers[0], 
true, "Called stop");
             }
 
             if(this.fileManager.StreamsOpen)
@@ -368,7 +370,7 @@
             PeerConnectionID id;
 
             // First attempt to resume downloading (just in case we've stalled 
for whatever reason)
-            lock (this.listLock)
+            lock (this.resumeLock)
                 if (this.peers.DownloadQueue.Count > 0 || 
this.peers.UploadQueue.Count > 0)
                     this.ResumePeers();
 
@@ -376,6 +378,8 @@
             DateTime nintySecondsAgo = nowTime.AddSeconds(-90);
             DateTime onhundredAndEightySecondsAgo = nowTime.AddSeconds(-180);
 
+            ClientEngine.ConnectionManager.TryConnect();
+
             lock (this.listLock)
             {
                 if (counter % (1000 / ClientEngine.TickLength) == 0)     // 
Call it every second... ish
@@ -434,7 +438,10 @@
                         }
 
                         if (!(id.Peer.Connection.ProcessingQueue) && 
id.Peer.Connection.QueueLength > 0)
-                            ClientEngine.ConnectionManager.ProcessQueue(id);
+                        {
+                            id.Peer.Connection.ProcessingQueue = true;
+                            
ClientEngine.ConnectionManager.MessageHandler.EnqueueSend(id);
+                        }
                     }
                 }
 
@@ -462,7 +469,7 @@
                         this.trackerManager.Announce(TorrentEvent.None);
                     }
                 }
-                if (counter % 40 == 0)
+                if (counter % (1000 / ClientEngine.TickLength) == 0)
                     
this.rateLimiter.UpdateDownloadChunks((int)(this.settings.MaxDownloadSpeed * 
1024 * 1.1),
                                                           
(int)(this.settings.MaxUploadSpeed * 1024 * 1.1),
                                                           
(int)(this.DownloadSpeed()),
@@ -641,22 +648,19 @@
         /// <param name="downloading"></param>
         internal void ResumePeers()
         {
-            lock (this.listLock)
-            {
-                if (this.state == TorrentState.Paused)
-                    return;
+            if (this.state == TorrentState.Paused)
+                return;
 
-                // While there are peers queued in the list and i haven't used 
my download allowance, resume downloading
-                // from that peer. Don't resume if there are more than 20 
queued writes in the download queue.
-                while (this.peers.DownloadQueue.Count > 0 && 
((this.rateLimiter.DownloadChunks > 0) || this.settings.MaxDownloadSpeed == 0))
-                    if (this.fileManager.QueuedWrites < 20)
-                        if 
(ClientEngine.ConnectionManager.ResumePeer(this.peers.Dequeue(PeerType.DownloadQueue),
 true) > ConnectionManager.ChunkLength / 2.0)
-                            Interlocked.Decrement(ref 
this.rateLimiter.DownloadChunks);
+            // While there are peers queued in the list and i haven't used my 
download allowance, resume downloading
+            // from that peer. Don't resume if there are more than 20 queued 
writes in the download queue.
+            while (this.peers.DownloadQueue.Count > 0 && 
((this.rateLimiter.DownloadChunks > 0) || this.settings.MaxDownloadSpeed == 0))
+                if (this.fileManager.QueuedWrites < 20)
+                    if 
(ClientEngine.ConnectionManager.ResumePeer(this.peers.Dequeue(PeerType.DownloadQueue),
 true) > ConnectionManager.ChunkLength / 2.0)
+                        Interlocked.Decrement(ref 
this.rateLimiter.DownloadChunks);
 
-                while (this.peers.UploadQueue.Count > 0 && 
((this.rateLimiter.UploadChunks > 0) || this.settings.MaxUploadSpeed == 0))
-                    if 
(ClientEngine.ConnectionManager.ResumePeer(this.peers.Dequeue(PeerType.UploadQueue),
 false) > ConnectionManager.ChunkLength / 2.0)
-                        Interlocked.Decrement(ref 
this.rateLimiter.UploadChunks);
-            }
+            while (this.peers.UploadQueue.Count > 0 && 
((this.rateLimiter.UploadChunks > 0) || this.settings.MaxUploadSpeed == 0))
+                if 
(ClientEngine.ConnectionManager.ResumePeer(this.peers.Dequeue(PeerType.UploadQueue),
 false) > ConnectionManager.ChunkLength / 2.0)
+                    Interlocked.Decrement(ref this.rateLimiter.UploadChunks);
         }
         #endregion
 

Modified: trunk/bitsharp/src/MonoTorrent.Client/PeerMessages/UnchokeMessage.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent.Client/PeerMessages/UnchokeMessage.cs        
2007-04-01 20:20:59 UTC (rev 75270)
+++ trunk/bitsharp/src/MonoTorrent.Client/PeerMessages/UnchokeMessage.cs        
2007-04-01 20:35:23 UTC (rev 75271)
@@ -93,8 +93,11 @@
             while (id.TorrentManager.AddPieceRequest(id)) { }
 
             // If we're not already processing the send queue, start 
processing it now
-            if (!id.Peer.Connection.ProcessingQueue)
-                ClientEngine.ConnectionManager.ProcessQueue(id);
+                       if (!id.Peer.Connection.ProcessingQueue)
+                       {
+                               id.Peer.Connection.ProcessingQueue = true;
+                               
ClientEngine.ConnectionManager.MessageHandler.EnqueueSend(id);
+                       }
         }
 
 

Modified: trunk/bitsharp/src/MonoTorrent.Client/Peers/Peer.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent.Client/Peers/Peer.cs 2007-04-01 20:20:59 UTC 
(rev 75270)
+++ trunk/bitsharp/src/MonoTorrent.Client/Peers/Peer.cs 2007-04-01 20:35:23 UTC 
(rev 75271)
@@ -51,6 +51,7 @@
         private bool isSeeder;
         private string location;
         private string peerId;
+               private DateTime lastConnectionAttempt;
 
         #endregion Private Fields
 
@@ -126,6 +127,11 @@
         }
 
 
+               internal DateTime LastConnectionAttempt
+               {
+                       get { return this.lastConnectionAttempt; }
+                       set { this.lastConnectionAttempt = value; }
+               }
         /// <summary>
         /// The location at which the peer can be connected to at
         /// </summary>

_______________________________________________
Mono-patches maillist  -  [email protected]
http://lists.ximian.com/mailman/listinfo/mono-patches

Reply via email to