public void Verify()
        {
            lock (verifierLock)
            {
                if (this.currentCount >= this.maxCount)
                {
                    throw new InvalidOperationException("The thread synchronization upstream is failing to restrict threads, reached or exceeded the max thread count");
                }

                if (this.currentCount < this.maxCount)
                {
                    this.currentCount++;
                }

                var signalled = this.verifier.WaitOne();
                if (!signalled)
                {
                    throw new InvalidOperationException("The semaphore and the current count should be in sync but they're not");
                }

                Monitor.Wait(this.verifierLock, WaitTimeout.Of(500).Milliseconds);

                this.verifier.Release();
                this.currentCount--;
            }
        }
Example #2
0
 public override void WriterAddAttribute(XmlWriter writer)
 {
     writer.WriteAttributeString("AttributeName", AttributeName);
     writer.WriteAttributeString("AttributeValue", AttributeValue);
     writer.WriteAttributeString("AttributeRegex", AttributeRegex ? "1" : "0");
     writer.WriteAttributeString("WaitTimeout", WaitTimeout.ToString());
     base.WriterAddAttribute(writer);
 }
        public Task Timeout(WaitTimeout state, IMessageHandlerContext context)
        {
            MarkAsComplete();

            var message = new SomethingSaidCompleted {
                Message = $"{Data.Message} and it's {Data.Temp}F outside and the favorite person is {Data.FavoritePerson}."
            };

            return(context.Publish(message));
        }
        public ContractBundle(IImmutableQueue<IContractCondition> preconditions = null,
                              IImmutableQueue<IContractCondition> postconditionsOnReturn = null,
                              IImmutableQueue<IContractCondition> postconditionsOnThrow = null,
                              IImmutableQueue<Action> instanceValidations = null,
                              int threadCountRestriction = 0,
                              WaitTimeout? threadCountRestrictionTimeout = null,
                              WaitHandle threadWaitHandleSignalRestriction = null,
                              WaitTimeout? threadWaitHandleSignalRestrictionTimeout = null)
        {
            this.Preconditions = preconditions.DefaultIfNull();
            this.PostconditionsOnReturn = postconditionsOnReturn.DefaultIfNull();
            this.PostconditionsOnThrow = postconditionsOnThrow.DefaultIfNull();
            this.InstanceValidations = instanceValidations.DefaultIfNull();
            this.ThreadCountRestriction = threadCountRestriction;
            this.ThreadCountRestrictionTimeout = threadCountRestrictionTimeout.DefaultIfNull();

            //Not defaulting this because null is checked for and verifying a default handle would be confusing to the caller
            this.ThreadWaitHandleSignalRestriction = threadWaitHandleSignalRestriction; 

            this.ThreadWaitHandleSignalRestrictionTimeout = threadWaitHandleSignalRestrictionTimeout.DefaultIfNull();
        }
Example #5
0
        public ContractBundle(IImmutableQueue <IContractCondition> preconditions          = null,
                              IImmutableQueue <IContractCondition> postconditionsOnReturn = null,
                              IImmutableQueue <IContractCondition> postconditionsOnThrow  = null,
                              IImmutableQueue <Action> instanceValidations = null,
                              int threadCountRestriction = 0,
                              WaitTimeout?threadCountRestrictionTimeout            = null,
                              WaitHandle threadWaitHandleSignalRestriction         = null,
                              WaitTimeout?threadWaitHandleSignalRestrictionTimeout = null)
        {
            this.Preconditions                 = preconditions.DefaultIfNull();
            this.PostconditionsOnReturn        = postconditionsOnReturn.DefaultIfNull();
            this.PostconditionsOnThrow         = postconditionsOnThrow.DefaultIfNull();
            this.InstanceValidations           = instanceValidations.DefaultIfNull();
            this.ThreadCountRestriction        = threadCountRestriction;
            this.ThreadCountRestrictionTimeout = threadCountRestrictionTimeout.DefaultIfNull();

            //Not defaulting this because null is checked for and verifying a default handle would be confusing to the caller
            this.ThreadWaitHandleSignalRestriction = threadWaitHandleSignalRestriction;

            this.ThreadWaitHandleSignalRestrictionTimeout = threadWaitHandleSignalRestrictionTimeout.DefaultIfNull();
        }
 public LockTransactionContractBundle(IImmutableQueue<IContractCondition> preconditions = null,
                                      IImmutableQueue<IContractCondition> postconditionsOnReturn = null,
                                      IImmutableQueue<IContractCondition> postconditionsOnThrow = null,
                                      IImmutableQueue<Action> instanceValidations = null,
                                      int threadCountRestriction = 0,
                                      WaitTimeout? threadCountRestrictionTimeout = null,
                                      WaitHandle threadWaitHandleSignalRestriction = null,
                                      WaitTimeout? threadWaitHandleSignalRestrictionTimeout = null,
                                      ILockTransactionMember[] transactionMembers = null,
                                      LockOrder lockOrder = Runtime.LockOrder.Unknown)
     :base(preconditions,
           postconditionsOnReturn,
           postconditionsOnThrow,
           instanceValidations,
           threadCountRestriction, 
           threadCountRestrictionTimeout,
           threadWaitHandleSignalRestriction,
           threadWaitHandleSignalRestrictionTimeout)
 {
     this.transactionMembers = transactionMembers.DefaultIfNull();
     this.lockOrder = lockOrder;
 }
Example #7
0
        private void TransferFiles(String sourceFolder, String baseFolder, String targetPath, String filter = "*.*", int speed = 1000, int filesAtOnce = 5)
        {
            cancel = false;
            String[]                 files          = GetFiles(sourceFolder, filter, SearchOption.AllDirectories);
            String                   xferId         = "";
            List <String>            thislist       = new List <String>();
            Object                   fileLocker     = new Object();
            long                     totalNumFiles  = files.Length;
            Dictionary <String, int> tries          = new Dictionary <String, int>();
            bool                     complete       = false;
            bool                     skippedLast    = false;
            long                     threadsStarted = 0;
            int skipLatency     = 0;
            int fileCopyLatency = 0;

            thislist.AddRange(files);

            UI(() =>
            {
                pbTransfer.Minimum = 0;
                pbTransfer.Maximum = (int)totalNumFiles;
                xferId             = tbUniqueId.Text.Trim();

                int.TryParse(tbSkipLatency.Text.Trim(), out skipLatency);
                int.TryParse(tbFileCopyLatency.Text.Trim(), out fileCopyLatency);

                tpfiles.Controls.Clear();
                lbErrorMsgs.Items.Clear();
            });

            Func <String> getFile = () =>
            {
                String thisFile = "";
                lock (fileLocker)
                {
                    if (thislist.Count > 0)
                    {
                        thisFile = thislist[0];
                        thislist.RemoveAt(0);
                    }
                }
                return(thisFile);
            };

            UI(() => lblStatus.Text = "Attempting to connect to the server ( Transfer Session 1 )");

            try
            {
                if (xferClient != null)
                {
                    try
                    {
                        xferClient.Close();
                    }
                    catch (Exception) { }
                }

                Thread.Sleep(500);

                xferClient = new Tools.FileTransfer.Client(remoteServerPort, remoteServerAddress.ToString(), xferId);
                xferClient.Connect();

                new Thread(() =>
                {
                    while (running && !complete)
                    {
                        if (!xferClient.Connected())
                        {
                            try
                            {
                                xferClient.Close();
                            }
                            catch (Exception) { Thread.Sleep(100); }

                            try
                            {
                                xferClient.Connect();
                            }
                            catch (Exception) { Thread.Sleep(100); }
                        }
                        else
                        {
                            Thread.Sleep(1);
                        }
                    }
                }).Start();
            }
            catch (Exception ex)
            {
                if (ex.Message.Equals(""))
                {
                    UI(() => lblStatus.Text = "The remote file transfer server could not be contacted.");
                }
                else
                {
                    UI(() => lblStatus.Text = ex.Message);
                }

                running = false;
                return;
            }

            lock (clientsLocker)
            {
                clients.Add(xferClient);
            }

            // Create a WaitTimeout that watches for these threads to report complete:
            WaitTimeout threadWaiter = null;

            ThreadPool.QueueUserWorkItem((o) =>
            {
                // wait as long as 24 hours (or until all worker threads report in):
                threadWaiter = new WaitTimeout(86400000, () => { return(!running); });
                threadWaiter.WaitOn(filesAtOnce, false);

                // Release the main thread:
                complete = true;

                // Wait for the connection monitor to exit...
                try
                {
                    Thread.Sleep(500);
                }
                catch (Exception) { }

                // Preform cleanup:
                clients.Clear();
                xferClient.Close();
            });

            for (int count = 0; count < filesAtOnce; count++)
            {
                ThreadPool.QueueUserWorkItem((o) =>
                {
                    int numDisConnects   = 0;
                    String streamName    = "TransferDataStream " + ((int)o).ToString() + numDisConnects.ToString();
                    bool reportedStarted = false;

                    String thisFile = getFile();

                    FileTransfer.Client.Transfer thisTransfer = xferClient.CreateNewTransfer((String msg) =>
                    {
                        UI(() =>
                        {
                            if (msg.Contains("not been modified"))
                            {
                                msg = msg.Replace("Transfer Failed", "Skipped");
                            }
                            lblStatus.Text = msg;

                            try
                            {
                                try
                                {
                                    pbTransfer.Value       = (int)(totalNumFiles - thislist.Count);
                                    gbOverallProgress.Text = "Over all progress: " +
                                                             ((int)(totalNumFiles - thislist.Count)).ToString() + @"/" + totalNumFiles.ToString();
                                }
                                catch (Exception) { }
                            }
                            catch (Exception) { }
                        });
                    });

                    // Create the TransferTracker Thread:
                    new Thread(() =>
                    {
                        TransferTracker tt = null;
                        bool ttCreated     = false;

                        UI(() =>
                        {
                            tt            = CreateTransferTracker();
                            tt.pb.Maximum = 100;
                            tt.pb.Value   = 0;
                            ttCreated     = true;
                        });

                        while (!ttCreated)
                        {
                            Thread.Sleep(1);
                        }

                        double percent     = 0;
                        String trackedFile = "";

                        while (running && !thisFile.Equals("") && !cancel && !complete)
                        {
                            lock (fileLocker)
                            {
                                trackedFile = thisFile;
                            }

                            if (!trackedFile.Equals("") && thisTransfer.IsComplete() == false)
                            {
                                UI(() =>
                                {
                                    if (!tt.gb.Text.Equals(Path.GetFileName(trackedFile)) && !tt.gb.Text.Equals(""))
                                    {
                                        tt.gb.Text = Path.GetFileName(trackedFile); tt.pb.Value = 0;
                                    }

                                    percent = thisTransfer.BytesWritten();
                                    percent = (percent / thisTransfer.length) * 100;

                                    if (percent > -1 && percent < 100)
                                    {
                                        if (tt.pb.Value != (int)percent)
                                        {
                                            tt.pb.Value = (int)percent;
                                        }
                                    }
                                });
                            }
                            else
                            {
                                UI(() => { if (tt.pb.Value != 100)
                                           {
                                               tt.pb.Value = 100;
                                           }
                                   });
                            }

                            Thread.Sleep(25);
                        }

                        UI(() => tt.pb.Value = 100);
                    }).Start();

                    // Send files
                    while (!thisFile.Equals("") && !cancel)
                    {
                        try
                        {
                            if (!xferClient.Connected() && !complete)
                            {
                                while (xferClient.Connected() == false && running && !cancel && !complete)
                                {
                                    Thread.Sleep(1);
                                }
                            }

                            // Speed throttling - important for controling CPU usage.
                            if (skippedLast)
                            {
                                Thread.Sleep(skipLatency);
                                skippedLast = false;
                            }
                            else
                            {
                                Thread.Sleep(fileCopyLatency);
                            }

                            // Send this file, and block until it completes:
                            if (!thisTransfer.Send(thisFile, baseFolder, targetPath, streamName, speed, true))
                            {
                                // If our transfer failed for any other reason then that the target file is identical...
                                if (!thisTransfer.errMsg.ToLower().Contains("not been modified"))
                                {
                                    // Sleep here for a short time to make sure we don't cause a dissconnection due to
                                    // bandwidth starvation:
                                    throw new Exception(thisTransfer.errMsg);
                                }
                                else
                                {
                                    skippedLast = true;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            UI(() => { lbErrorMsgs.Items.Add(streamName + ": " + ex.Message); });

                            if (ex.Message.Contains("connection lost") || ex.Message.Contains("target corrupt"))
                            {
                                lock (fileLocker)
                                {
                                    // Add it to the end so that there is time for it to be closed properly:
                                    thislist.Add(thisFile);
                                    numDisConnects += 1;
                                    streamName      = "TransferDataStream " + ((int)o).ToString() + numDisConnects.ToString();
                                }
                            }
                        }

                        if (!reportedStarted)
                        {
                            Interlocked.Increment(ref threadsStarted);
                            reportedStarted = true;
                        }

                        if (Interlocked.Read(ref threadsStarted) < filesAtOnce)
                        {
                            Thread.Sleep(100);
                        }

                        thisFile = getFile();
                    }

                    // Give things a change to finieh
                    Thread.Sleep(1000);

                    threadWaiter.ReportThreadComplete();
                }, count);
            }

            // We need to block until this all completes:
            while (!complete && running)
            {
                Thread.Sleep(1);
            }

            UI(() =>
            {
                lblStatus.Text = "Transfer complete.";
            });
        }
Example #8
0
        private void DoTransferLoop()
        {
            running = true;
            cancel  = false;

            String tmp          = "";
            String serverIp     = "";
            String sourceFolder = "";
            String targetFolder = "";
            String filter       = "";
            int    speed        = 1000;     // gigabit
            int    interval     = 0;
            int    filesAtOnce  = 5;

            TimeSpan minutes;
            DateTime timeout;

            bool        getValuesComplete = false;
            WaitTimeout wt;

            Action getConfig = () =>
            {
                // We need to make sure the values are set before the
                // main thread continues:
                getValuesComplete = false;
                wt = new WaitTimeout(1000, () => getValuesComplete);

                UI(() =>
                {
                    serverIp     = tbServerIp.Text.Trim();
                    sourceFolder = tbSourcefolder.Text.Trim();
                    targetFolder = tbTargetFolder.Text.Trim();
                    filter       = tbFilter.Text.Trim();
                    tmp          = tbSpeed.Text.Trim();

                    try
                    {
                        speed = int.Parse(tmp);
                    }
                    catch (Exception) { }

                    tmp = tbFilesAtOnce.Text.Trim();

                    try
                    {
                        filesAtOnce = int.Parse(tmp);
                    }
                    catch (Exception) { }

                    tmp = cbInterval.Items[cbInterval.SelectedIndex].ToString();

                    try
                    {
                        remoteServerAddress = System.Net.IPAddress.Parse(serverIp);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("The currently entered IP Address is invalid. This Sync services have been disabled.",
                                        "Problem saving configuration!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    try
                    {
                        remoteServerPort = UInt16.Parse(tbServerPort.Text.Trim());
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("The currently entered port number is invalid. This Sync services have been disabled.",
                                        "Problem saving configuration!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    getValuesComplete = true;
                });

                wt.Wait();

                tmp = tmp.Replace("Every ", "");
                if (tmp.Contains("minute"))
                {
                    tmp      = Regex.Split(tmp, " minute")[0];
                    interval = int.Parse(tmp);
                }

                if (tmp.Contains(" Hours"))
                {
                    tmp      = Regex.Split(tmp, " Hours")[0];
                    interval = int.Parse(tmp);
                    interval = interval * 60;
                }

                minutes = new TimeSpan(0, interval, 0);
                timeout = DateTime.Now;

                wt.Close();
            };

            while (running && !cancel)
            {
                try
                {
                    // Refresh the config every time this runs. This way, if they are
                    // changed, the changes are reflected in the next run of the transfer.
                    getConfig();
                    TransferFiles(sourceFolder, sourceFolder, targetFolder, filter, speed, filesAtOnce);
                }
                catch (Exception)
                {
                    // Log exceptions here
                }

                timeout = DateTime.Now.AddMinutes(interval);
                while (DateTime.Now < timeout && running && !cancel)
                {
                    Thread.Sleep(1);
                }
            }
        }
 private IContractBundle Copy(IImmutableQueue<IContractCondition> preconditions = null,
                              IImmutableQueue<IContractCondition> postconditionsOnReturn = null,
                              IImmutableQueue<IContractCondition> postconditionsOnThrow = null,
                              IImmutableQueue<Action> instanceValidations = null,
                              int? threadCountRestriction = null,
                              WaitTimeout? threadCountRestrictionTimeout = null,
                              WaitHandle threadWaitHandleSignalRestriction = null,
                              WaitTimeout? threadWaitHandleSignalRestrictionTimeout = null)
 {
     return new ContractBundle(preconditions ?? this.Preconditions,
                               postconditionsOnReturn ?? this.PostconditionsOnReturn,
                               postconditionsOnThrow ?? this.PostconditionsOnThrow,
                               instanceValidations ?? this.InstanceValidations,
                               threadCountRestriction ?? this.ThreadCountRestriction,
                               threadCountRestrictionTimeout ?? this.ThreadCountRestrictionTimeout,
                               threadWaitHandleSignalRestriction ?? this.ThreadWaitHandleSignalRestriction,
                               threadWaitHandleSignalRestrictionTimeout ?? this.ThreadWaitHandleSignalRestrictionTimeout);
 }
 public IContractBundle AddThreadWaitHandleRestrictionFor(WaitHandle handle, WaitTimeout timeout)
 {
     return Copy(threadWaitHandleSignalRestriction: handle, threadWaitHandleSignalRestrictionTimeout: timeout);
 }
 public IContractBundle AddThreadCountRestrictionOf(int count, WaitTimeout timeout)
 {
     return Copy(threadCountRestriction: count, threadCountRestrictionTimeout: timeout);
 }
Example #12
0
 public IContractBundle AddThreadWaitHandleRestrictionFor(WaitHandle handle, WaitTimeout timeout)
 {
     return(Copy(threadWaitHandleSignalRestriction: handle, threadWaitHandleSignalRestrictionTimeout: timeout));
 }
Example #13
0
 public IContractBundle AddThreadCountRestrictionOf(int count, WaitTimeout timeout)
 {
     return(Copy(threadCountRestriction: count, threadCountRestrictionTimeout: timeout));
 }
        public TPublicContext ToMaxOf(int number, WaitTimeout timeout = default(WaitTimeout))
        {
            var elevatedContractBundle = this.contractBundle.AddThreadCountRestrictionOf(number, timeout);

            return(this.context.Copy(this.bundle, elevatedContractBundle));
        }
        public TPublicContext ByWaitingFor(WaitHandle handle, WaitTimeout timeout = default(WaitTimeout))
        {
            var elevatedContractBundle = this.contractBundle.AddThreadWaitHandleRestrictionFor(handle, timeout);

            return(this.context.Copy(this.bundle, elevatedContractBundle));
        }