コード例 #1
0
ファイル: Test.cs プロジェクト: tomahock/sapo-broker
        public bool Run(int numberOfRuns)
        {
            bool result = true;

            if (this.CanSkipTest)
            {
                Console.WriteLine("Test skiped");
                return(true);
            }
            Console.WriteLine("Building test - " + Name);
            Build();

            Console.WriteLine("Initializing  test - " + Name);
            foreach (PreRequisite prereq in preRequisites)
            {
                if (prereq.Call().IsFailure())
                {
                    Console.WriteLine("##PreRequisite execution failed - " + prereq.Name);
                }
            }

            Console.WriteLine("Performing test - " + Name);

            WaitHandle[] handles = new WaitHandle[consequences.Count + 1];
            int          index   = 0;

            foreach (Consequence consequence in consequences)
            {
                Consequence tmpConsequence = consequence; // if you know closures you understand this.
                ThreadPool.QueueUserWorkItem(
                    (o) =>
                {
                    tmpConsequence.Call();
                }
                    );

                handles[index++] = consequence.ManualResetEvent;
            }

            ThreadPool.QueueUserWorkItem(
                (o) => {
                action.Call();
            }
                );
            handles[index] = action.ManualResetEvent;


            bool res = WaitHandle.WaitAll(handles, this.Timeout, false);


            if (!res)
            {
                Console.WriteLine("### Action or consquences timedout.");
            }

            if (!DisplayStepResult(action))
            {
                result = false;
            }


            foreach (Consequence consequence in consequences)
            {
                if (!DisplayStepResult(consequence))
                {
                    result = false;
                }
            }

            Console.WriteLine("Finalizing test - " + Name);

            foreach (Epilogue epilogue in epilogues)
            {
                if (epilogue.Call().IsFailure())
                {
                    Console.WriteLine("##Epilogue execution failed - " + epilogue.Name);
                }
            }

            return(result);
        }
コード例 #2
0
        /// <summary>
        /// Makes a Query where the expected Result is a SparqlResultSet ie. SELECT and ASK Queries
        /// </summary>
        /// <param name="handler">Results Handler to process the results</param>
        /// <param name="sparqlQuery">SPARQL Query String</param>
        /// <exception cref="RdfQueryException">Thrown if any of the requests to the endpoints fail</exception>
        /// <exception cref="RdfQueryTimeoutException">Thrown if not all the requests complete within the set timeout</exception>
        public override void QueryWithResultSet(ISparqlResultsHandler handler, string sparqlQuery)
        {
            //If no endpoints do nothing
            if (this._endpoints.Count == 0)
            {
                return;
            }

            //Fire off all the Asychronous Requests
            List <AsyncQueryWithResultSet> asyncCalls   = new List <AsyncQueryWithResultSet>();
            List <IAsyncResult>            asyncResults = new List <IAsyncResult>();
            int count = 0;

            foreach (SparqlRemoteEndpoint endpoint in this._endpoints)
            {
                //Limit the number of simultaneous requests we make to the user defined level (default 4)
                //We do this limiting check before trying to issue a request so that when the last request
                //is issued we'll always drop out of the loop and move onto our WaitAll()
                while (count >= this._maxSimultaneousRequests)
                {
                    //First check that the count of active requests is accurate
                    int active = asyncResults.Count(r => !r.IsCompleted);
                    if (active < count)
                    {
                        //Some of the requests have already completed so we don't need to wait
                        count = active;
                        break;
                    }
                    else if (active > count)
                    {
                        //There are more active requests then we thought
                        count = active;
                    }

                    //While the number of requests is at/above the maximum we'll wait for any of the requests to finish
                    //Then we can decrement the count and if this drops back below our maximum then we'll go back into the
                    //main loop and fire off our next request
                    WaitHandle.WaitAny(asyncResults.Select(r => r.AsyncWaitHandle).ToArray());
                    count--;
                }

                //Make an asynchronous query to the next endpoint
                AsyncQueryWithResultSet d = new AsyncQueryWithResultSet(endpoint.QueryWithResultSet);
                asyncCalls.Add(d);
                IAsyncResult asyncResult = d.BeginInvoke(sparqlQuery, null, null);
                asyncResults.Add(asyncResult);
                count++;
            }

            //Wait for all our requests to finish
            int waitTimeout = (base.Timeout > 0) ? base.Timeout : System.Threading.Timeout.Infinite;

            WaitHandle.WaitAll(asyncResults.Select(r => r.AsyncWaitHandle).ToArray(), waitTimeout);

            //Check for and handle timeouts
            if (!this._ignoreFailedRequests && !asyncResults.All(r => r.IsCompleted))
            {
                for (int i = 0; i < asyncCalls.Count; i++)
                {
                    try
                    {
                        asyncCalls[i].EndInvoke(asyncResults[i]);
                    }
                    catch
                    {
                        //Exceptions don't matter as we're just ensuring all the EndInvoke() calls are made
                    }
                }
                throw new RdfQueryTimeoutException("Federated Querying failed due to one/more endpoints failing to return results within the Timeout specified which is currently " + (base.Timeout / 1000) + " seconds");
            }

            //Now merge all the results together
            HashSet <String> varsSeen = new HashSet <string>();
            bool             cont     = true;

            for (int i = 0; i < asyncCalls.Count; i++)
            {
                //Retrieve the result for this call
                AsyncQueryWithResultSet call = asyncCalls[i];
                SparqlResultSet         partialResult;
                try
                {
                    partialResult = call.EndInvoke(asyncResults[i]);
                }
                catch (Exception ex)
                {
                    if (!this._ignoreFailedRequests)
                    {
                        //Clean up in the event of an error
                        for (int j = i + 1; j < asyncCalls.Count; j++)
                        {
                            try
                            {
                                asyncCalls[j].EndInvoke(asyncResults[j]);
                            }
                            catch
                            {
                                //Exceptions don't matter as we're just ensuring all the EndInvoke() calls are made
                            }
                        }

                        //If a single request fails then the entire query fails
                        throw new RdfQueryException("Federated Querying failed due to the query against the endpoint '" + this._endpoints[i].Uri.AbsoluteUri + "' failing", ex);
                    }
                    else
                    {
                        //If we're ignoring failed requests we continue here
                        continue;
                    }
                }

                //Merge the result into the final results
                //If the handler has previously told us to stop we skip this step
                if (cont)
                {
                    foreach (String variable in partialResult.Variables)
                    {
                        cont = handler.HandleVariable(variable);
                        //Stop if handler tells us to
                        if (!cont)
                        {
                            break;
                        }
                    }

                    if (cont)
                    {
                        foreach (SparqlResult result in partialResult.Results)
                        {
                            cont = handler.HandleResult(result);
                            //Stop if handler tells us to
                            if (!cont)
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }
コード例 #3
0
ファイル: Form1.cs プロジェクト: xl711436/CodeRecord
        private void Btn_PollWait_Multy_Click(object sender, EventArgs e)
        {
            List <string> webSites = new List <string>()
            {
                "http://www.cnblogs.com",
                "http://www.baidu.com",
                "http://www.csdn.com",
                "http://www.baidu.com",
                "http://www.cnblogs.com",
                "http://www.csdn.com",
                "http://www.cnblogs.com",
                "http://www.baidu.com",
                "http://www.csdn.com",
            };
            List <MyDelegate> delegateList = new List <MyDelegate>()
            {
                new MyDelegate((string para) =>
                {
                    System.Diagnostics.Trace.WriteLine("delegate1 thread:" + Thread.CurrentThread.ManagedThreadId);
                    Thread.Sleep(3000);
                    return(para.Length);
                }),
                new MyDelegate((string para) =>
                {
                    System.Diagnostics.Trace.WriteLine("delegate2 thread:" + Thread.CurrentThread.ManagedThreadId);
                    Thread.Sleep(6000);
                    return(para.Length);
                }),
                new MyDelegate((string para) =>
                {
                    System.Diagnostics.Trace.WriteLine("delegate3 thread:" + Thread.CurrentThread.ManagedThreadId);
                    Thread.Sleep(4000);
                    return(para.Length);
                }),
            };

            List <IAsyncResult> resultList = new List <IAsyncResult>()
            {
                delegateList[0].BeginInvoke("Leslie", null, null),
                delegateList[1].BeginInvoke("jackson", null, null),
                delegateList[2].BeginInvoke("Mike", null, null)
            };

            WaitHandle[] handleList = resultList.Select(p => p.AsyncWaitHandle).ToArray();

            foreach (string curWebsite in webSites)
            {
                using (WebClient wc = new WebClient())
                {
                    string curContent = wc.DownloadString(new Uri(curWebsite));
                    Thread.Sleep(1000);
                    Tb_ThreadInfo.Text += curWebsite + ": length:" + curContent.Length.ToString() + Environment.NewLine;
                }

                if (WaitHandle.WaitAll(handleList, 100))
                {
                    System.Diagnostics.Trace.WriteLine("main thread:" + Thread.CurrentThread.ManagedThreadId);
                    break;
                }
            }

            for (int i = 0; i < delegateList.Count; i++)
            {
                int data = delegateList[i].EndInvoke(resultList[i]);
                Tb_ThreadInfo.Text += ("result:" + data.ToString() + Environment.NewLine);
            }
        }
コード例 #4
0
 internal static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
 {
     return(WaitHandle.WaitAll(waitHandles, millisecondsTimeout));
 }
コード例 #5
0
        private void ClientGameLoop(object client)
        {
            NetworkCommunicator networkCommunicator = (NetworkCommunicator)client;
            ManualResetEvent    sentDataThisTurn    = new ManualResetEvent(false);
            ManualResetEvent    endOfTurnWait       = new ManualResetEvent(false);

            try
            {
                string data = string.Empty;

                _playersThatSentDataThisTurnList.Add(sentDataThisTurn);
                _endOfTurnWaitList.Add(endOfTurnWait);
                _currentTurnClientActions.Add(new PlayerAction(networkCommunicator.RemoteEndPoint.ToString(), MessageConstants.PlayerActionNone));

                _log.InfoFormat("Client {0} connected running on thread: {1}, waiting for start game / 1st turn data", networkCommunicator.RemoteEndPoint, Thread.CurrentThread.ManagedThreadId);
                data = networkCommunicator.ReceiveData();
                bool readFromClient = false;

                if (data == MessageConstants.StartGame)
                {
                    readFromClient = true;
                    RunGame();
                    foreach (NetworkCommunicator clientPlayer in _players)
                    {
                        clientPlayer.SendData(MessageConstants.GameStarting);
                    }
                    _completeGameState.StartNewGame(_currentTurnClientActions);
                }

                // Loop to receive all the data sent by the client.
                // this is now the main game loop for the game - 1 thread per client
                bool gameIsOn = true;
                while (gameIsOn) //issue [B.2.3] of the design document
                {
                    if (readFromClient)
                    {
                        data = networkCommunicator.ReceiveData();
                    }
                    else
                    {
                        readFromClient = true;
                    }

                    foreach (PlayerAction action in _currentTurnClientActions)
                    {
                        if (action.PlayerID == networkCommunicator.RemoteEndPoint.ToString())
                        {
                            action.Action = data;
                        }
                    }
                    sentDataThisTurn.Set();

                    _gameStateProcessed.WaitOne();

                    networkCommunicator.SendData(_completeGameState.ToString());
                    endOfTurnWait.Set();
                    WaitHandle.WaitAll(_endOfTurnWaitArray); //issue [B.2.3] of the design document
                    _gameStateProcessed.Reset();
                }
            }
            catch (Exception ex)
            {
                ErrorUtil.WriteError(ex);
                throw;
            }
            finally
            {
                sentDataThisTurn.Close();
                endOfTurnWait.Close();
                networkCommunicator.Dispose();
            }
        }
コード例 #6
0
        public static void DemoWithMultipleMutex()
        {
            var tasks = new List <Task>();

            var c1 = new Conta();
            var c2 = new Conta();

            var mutex1 = new Mutex();
            var mutex2 = new Mutex();

            for (int i = 0; i < 10; i++)
            {
                tasks.Add(Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < 1000; i++)
                    {
                        bool hasLock = mutex1.WaitOne();
                        try
                        {
                            c1.Deposito(100);
                        }
                        finally
                        {
                            if (hasLock)
                            {
                                mutex1.ReleaseMutex();
                            }
                        }
                    }
                }));

                tasks.Add(Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < 1000; i++)
                    {
                        bool hasLock = mutex1.WaitOne();
                        try
                        {
                            c1.Saque(100);
                        }
                        finally
                        {
                            if (hasLock)
                            {
                                mutex1.ReleaseMutex();
                            }
                        }
                    }
                }));
            }

            for (int i = 0; i < 10; i++)
            {
                tasks.Add(Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < 1000; i++)
                    {
                        bool hasLock = mutex2.WaitOne();
                        try
                        {
                            c2.Deposito(100);
                        }
                        finally
                        {
                            if (hasLock)
                            {
                                mutex2.ReleaseMutex();
                            }
                        }
                    }
                }));

                tasks.Add(Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < 1000; i++)
                    {
                        bool hasLock = mutex2.WaitOne();
                        try
                        {
                            c2.Saque(100);
                        }
                        finally
                        {
                            if (hasLock)
                            {
                                mutex2.ReleaseMutex();
                            }
                        }
                    }
                }));

                tasks.Add(Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < 1000; i++)
                    {
                        bool hasLock = WaitHandle.WaitAll(new[] { mutex1, mutex2 });
                        try
                        {
                            c1.Tansferir(c2, i);
                        }
                        finally
                        {
                            if (hasLock)
                            {
                                mutex1.ReleaseMutex();
                                mutex2.ReleaseMutex();
                            }
                        }
                    }
                }));

                tasks.Add(Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < 1000; i++)
                    {
                        bool hasLock = WaitHandle.WaitAll(new[] { mutex1, mutex2 });
                        try
                        {
                            c2.Tansferir(c1, i);
                        }
                        finally
                        {
                            if (hasLock)
                            {
                                mutex1.ReleaseMutex();
                                mutex2.ReleaseMutex();
                            }
                        }
                    }
                }));
            }
            Task.WaitAll(tasks.ToArray());

            Console.WriteLine($"Saldo c1: {c1.Saldo}");
            Console.WriteLine($"Saldo c2: {c2.Saldo}");
        }
コード例 #7
0
        static void Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            ThreadPool.SetMaxThreads(4, 4);

            // Get pdf files collection
            string pdfFilesCollection = "Input\\";

            string[] pdfFiles = Directory.GetFiles(pdfFilesCollection, "*.pdf", SearchOption.AllDirectories);
            List < Stream & dt; streams = new List <Stream>();

            // Wait handles
            List <ManualResetEvent> manualResetEvents = new List <ManualResetEvent>();

            // Create streams
            for (int i = 0; i < pdfFiles.Length; i++)
            {
                FileStream stream = new FileStream(pdfFiles[i], FileMode.Open, FileAccess.Read);
                streams.Add(stream);
            }

            // Queue work items for documents
            for (int i = 0; i < pdfFiles.Length; i++)
            {
                ThreadPool.QueueUserWorkItem(RenderFile, new object[] { streams[i], pdfFiles[i], manualResetEvents });
            }

            // Wait while all documents isn't ready
            int eventsCount = pdfFiles.Length - 1;

            while (eventsCount > 0)
            {
                WaitHandle[] events;
                lock (syncRoot)
                {
                    events = manualResetEvents.ToArray();
                }
                if (events.Length == 0)
                {
                    continue;
                }

                for (int i = 0; i < events.Length; i++)
                {
                    WaitHandle.WaitAll(new[] { events[i] });
                    lock (syncRoot)
                    {
                        manualResetEvents.Remove((ManualResetEvent)events[i]);
                        eventsCount--;
                    }
                }
            }

            // Close streams
            for (int i = 0; i < streams.Count; i++)
            {
                streams[i].Close();
            }

            // Show resulting time
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed.TotalMilliseconds);
            Console.ReadKey();
        }
コード例 #8
0
ファイル: PublishingSpec.cs プロジェクト: jangocheng/mqtt-2
        public async Task when_publish_without_clean_session_then_pending_messages_are_sent_when_reconnect()
        {
            var client1 = await GetClientAsync();

            var client1Done     = new ManualResetEventSlim();
            var client1Received = 0;

            var client2 = await GetClientAsync();

            var client2Id       = client2.Id;
            var client2Done     = new ManualResetEventSlim();
            var client2Received = 0;

            var topic = "topic/foo/bar";
            var messagesBeforeDisconnect = 3;
            var messagesAfterReconnect   = 2;

            await client1.SubscribeAsync(topic, MqttQualityOfService.AtLeastOnce);

            await client2.SubscribeAsync(topic, MqttQualityOfService.AtLeastOnce);

            var subscription1 = client1
                                .MessageStream
                                .Where(m => m.Topic == topic)
                                .Subscribe(m => {
                client1Received++;

                if (client1Received == messagesBeforeDisconnect)
                {
                    client1Done.Set();
                }
            });

            var subscription2 = client2
                                .MessageStream
                                .Where(m => m.Topic == topic)
                                .Subscribe(m => {
                client2Received++;

                if (client2Received == messagesBeforeDisconnect)
                {
                    client2Done.Set();
                }
            });

            for (var i = 1; i <= messagesBeforeDisconnect; i++)
            {
                var testMessage = GetTestMessage(i);
                var message     = new MqttApplicationMessage(topic, Serializer.Serialize(testMessage));

                await client1.PublishAsync(message, MqttQualityOfService.AtLeastOnce, retain : false);
            }

            var completed = WaitHandle.WaitAll(new WaitHandle[] { client1Done.WaitHandle, client2Done.WaitHandle }, TimeSpan.FromSeconds(Configuration.WaitTimeoutSecs));

            Assert.True(completed, $"Messages before disconnect weren't all received. Client 1 received: {client1Received}, Client 2 received: {client2Received}");
            Assert.Equal(messagesBeforeDisconnect, client1Received);
            Assert.Equal(messagesBeforeDisconnect, client2Received);

            await client2.DisconnectAsync();

            subscription1.Dispose();
            client1Received = 0;
            client1Done.Reset();
            subscription2.Dispose();
            client2Received = 0;
            client2Done.Reset();

            var client1OldMessagesReceived = 0;
            var client2OldMessagesReceived = 0;

            subscription1 = client1
                            .MessageStream
                            .Where(m => m.Topic == topic)
                            .Subscribe(m => {
                var testMessage = Serializer.Deserialize <TestMessage>(m.Payload);

                if (testMessage.Id > messagesBeforeDisconnect)
                {
                    client1Received++;
                }
                else
                {
                    client1OldMessagesReceived++;
                }

                if (client1Received == messagesAfterReconnect)
                {
                    client1Done.Set();
                }
            });

            subscription2 = client2
                            .MessageStream
                            .Where(m => m.Topic == topic)
                            .Subscribe(m => {
                var testMessage = Serializer.Deserialize <TestMessage>(m.Payload);

                if (testMessage.Id > messagesBeforeDisconnect)
                {
                    client2Received++;
                }
                else
                {
                    client2OldMessagesReceived++;
                }

                if (client2Received == messagesAfterReconnect)
                {
                    client2Done.Set();
                }
            });

            for (var i = messagesBeforeDisconnect + 1; i <= messagesBeforeDisconnect + messagesAfterReconnect; i++)
            {
                var testMessage = GetTestMessage(i);
                var message     = new MqttApplicationMessage(topic, Serializer.Serialize(testMessage));

                await client1.PublishAsync(message, MqttQualityOfService.AtLeastOnce, retain : false);
            }

            await client2.ConnectAsync(new MqttClientCredentials(client2Id), cleanSession : false);

            completed = WaitHandle.WaitAll(new WaitHandle[] { client1Done.WaitHandle, client2Done.WaitHandle }, TimeSpan.FromSeconds(Configuration.WaitTimeoutSecs));

            Assert.True(completed, $"Messages after re connect weren't all received. Client 1 received: {client1Received}, Client 2 received: {client2Received}");
            Assert.Equal(messagesAfterReconnect, client1Received);
            Assert.Equal(messagesAfterReconnect, client2Received);
            Assert.Equal(0, client1OldMessagesReceived);
            Assert.Equal(0, client2OldMessagesReceived);

            await client1.UnsubscribeAsync(topic)
            .ConfigureAwait(continueOnCapturedContext: false);

            await client2.UnsubscribeAsync(topic)
            .ConfigureAwait(continueOnCapturedContext: false);

            client1.Dispose();
            client2.Dispose();
        }
コード例 #9
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="downloadFolder">The file to which the report is downloaded.
        /// </param>
        public void Run(AdWordsUser user, string downloadFolder)
        {
            // Increase the number of HTTP connections we can do in parallel.
            System.Net.ServicePointManager.DefaultConnectionLimit = 100;

            try {
                // Start the rate limiter with an initial value of zero, so that all
                // threads block immediately.
                Semaphore rateLimiter = new Semaphore(0, MAX_REPORT_DOWNLOADS_IN_PARALLEL);

                // Get all the advertiser accounts under this manager account.
                List <long> allCustomerIds = GetDescendantAdvertiserAccounts(user);

                // Create a concurrent queue of customers so that all threads can work
                // on the collection in parallel.
                ConcurrentQueue <long> customerQueue = new ConcurrentQueue <long>(allCustomerIds);

                // Create queues to keep track of successful and failed report downloads.
                ConcurrentQueue <SuccessfulReportDownload> reportsSucceeeded =
                    new ConcurrentQueue <SuccessfulReportDownload>();
                ConcurrentQueue <FailedReportDownload> reportsFailed =
                    new ConcurrentQueue <FailedReportDownload>();

                // Keep an array of events. This is used by the main thread to wait for
                // all worker threads to join.
                ManualResetEvent[] doneEvents = new ManualResetEvent[MAX_NUMBER_OF_THREADS];

                // The list of threads to download reports.
                Thread[] threads = new Thread[MAX_NUMBER_OF_THREADS];

                // The data for each thread.
                ReportDownloadData[] threadData = new ReportDownloadData[MAX_NUMBER_OF_THREADS];

                // The query to be run on each account.
                string query = "SELECT CampaignId, AdGroupId, Impressions, Clicks, Cost from " +
                               "ADGROUP_PERFORMANCE_REPORT where AdGroupStatus IN [ENABLED, PAUSED] " +
                               "DURING LAST_7_DAYS";

                // Initialize the threads and their data.
                for (int i = 0; i < MAX_NUMBER_OF_THREADS; i++)
                {
                    doneEvents[i] = new ManualResetEvent(false);
                    threadData[i] = new ReportDownloadData()
                    {
                        Config            = (AdWordsAppConfig)(user.Config.Clone()),
                        DownloadFolder    = downloadFolder,
                        SignalEvent       = doneEvents[i],
                        ThreadIndex       = i,
                        QuotaLock         = rateLimiter,
                        CustomerIdQueue   = customerQueue,
                        SuccessfulReports = reportsSucceeeded,
                        FailedReports     = reportsFailed
                    };

                    threads[i] = new Thread(threadData[i].ThreadCallback);
                }

                // Start the threads. Since the initial value of rate limiter is zero,
                // all threads will block immediately.
                for (int i = 0; i < threads.Length; i++)
                {
                    threads[i].Start(query);
                }

                // Now reset the rate limiter so all threads can start downloading reports.
                rateLimiter.Release(MAX_REPORT_DOWNLOADS_IN_PARALLEL);

                // Wait for all threads in pool to complete.
                WaitHandle.WaitAll(doneEvents);
                Console.WriteLine("Download completed, results:");

                Console.WriteLine("Successful reports:");
                while (!reportsSucceeeded.IsEmpty)
                {
                    SuccessfulReportDownload success = null;
                    if (reportsSucceeeded.TryDequeue(out success))
                    {
                        Console.WriteLine("Client ID: {0}, Path: {1}", success.CustomerId, success.Path);
                    }
                }

                Console.WriteLine("Failed reports:");
                while (!reportsFailed.IsEmpty)
                {
                    FailedReportDownload failure = null;
                    if (reportsFailed.TryDequeue(out failure))
                    {
                        Console.WriteLine("Client ID: {0}, Cause: {1}", failure.CustomerId,
                                          failure.Exception.Message);
                    }
                }

                Console.WriteLine("All reports are downloaded.");
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to download reports.", e);
            }
        }
コード例 #10
0
        static void Main(string[] args)
        {
            var tasks = new List <Task>();
            var ba    = new BankAccount();
            var ba2   = new BankAccount();

            Mutex mutex  = new Mutex();
            Mutex mutex2 = new Mutex();

            for (int i = 0; i < 10; i++)
            {
                tasks.Add(Task.Factory.StartNew(() =>
                {
                    for (int j = 0; j < 1000; j++)
                    {
                        bool haveLock = mutex.WaitOne();
                        try
                        {
                            ba.Deposit(100);
                        }
                        finally
                        {
                            if (haveLock)
                            {
                                mutex.ReleaseMutex();
                            }
                        }
                    }
                }));

                tasks.Add(Task.Factory.StartNew(() =>
                {
                    for (int j = 0; j < 1000; j++)
                    {
                        bool haveLock = mutex2.WaitOne();
                        try
                        {
                            ba2.Withdraw(100);
                        }
                        finally
                        {
                            if (haveLock)
                            {
                                mutex2.ReleaseMutex();
                            }
                        }
                    }
                }));

                tasks.Add(Task.Factory.StartNew(() => {
                    for (int k = 0; k < 1000; k++)
                    {
                        bool haveLock = WaitHandle.WaitAll(new[] { mutex, mutex2 });
                        try
                        {
                            ba.Transfer(ba2, 1);
                        }
                        finally
                        {
                            mutex.ReleaseMutex();
                            mutex2.ReleaseMutex();
                        }
                    }
                }));
            }

            Task.WaitAll(tasks.ToArray());

            Console.WriteLine($"Final balance is {ba.Balance}.");
        }
コード例 #11
0
ファイル: PublishingSpec.cs プロジェクト: jangocheng/mqtt-2
        public async Task when_publish_message_to_topic_then_message_is_dispatched_to_subscribers()
        {
            var count = GetTestLoad();

            var guid        = Guid.NewGuid().ToString();
            var topicFilter = guid + "/#";
            var topic       = guid;

            var publisher = await GetClientAsync();

            var subscriber1 = await GetClientAsync();

            var subscriber2 = await GetClientAsync();

            var subscriber1Done     = new ManualResetEventSlim();
            var subscriber2Done     = new ManualResetEventSlim();
            var subscriber1Received = 0;
            var subscriber2Received = 0;

            await subscriber1.SubscribeAsync(topicFilter, MqttQualityOfService.AtMostOnce)
            .ConfigureAwait(continueOnCapturedContext: false);

            await subscriber2.SubscribeAsync(topicFilter, MqttQualityOfService.AtMostOnce)
            .ConfigureAwait(continueOnCapturedContext: false);

            subscriber1.MessageStream
            .Subscribe(m => {
                if (m.Topic == topic)
                {
                    subscriber1Received++;

                    if (subscriber1Received == count)
                    {
                        subscriber1Done.Set();
                    }
                }
            });

            subscriber2.MessageStream
            .Subscribe(m => {
                if (m.Topic == topic)
                {
                    subscriber2Received++;

                    if (subscriber2Received == count)
                    {
                        subscriber2Done.Set();
                    }
                }
            });

            var tasks = new List <Task> ();

            for (var i = 1; i <= count; i++)
            {
                var testMessage = GetTestMessage(i);
                var message     = new MqttApplicationMessage(topic, Serializer.Serialize(testMessage));

                tasks.Add(publisher.PublishAsync(message, MqttQualityOfService.AtMostOnce));
            }

            await Task.WhenAll(tasks);

            var completed = WaitHandle.WaitAll(new WaitHandle[] { subscriber1Done.WaitHandle, subscriber2Done.WaitHandle }, TimeSpan.FromSeconds(Configuration.WaitTimeoutSecs));

            Assert.Equal(count, subscriber1Received);
            Assert.Equal(count, subscriber2Received);
            Assert.True(completed);

            await subscriber1.UnsubscribeAsync(topicFilter)
            .ConfigureAwait(continueOnCapturedContext: false);

            await subscriber2.UnsubscribeAsync(topicFilter)
            .ConfigureAwait(continueOnCapturedContext: false);

            subscriber1.Dispose();
            subscriber2.Dispose();
            publisher.Dispose();
        }
コード例 #12
0
ファイル: CHTAgentStub.cs プロジェクト: radtek/agent-windows
        private void ThreadProc(object arg)
        {
            try
            {
                ManualResetEvent quitEvent = (ManualResetEvent)arg;
                var    proc                    = Process.GetCurrentProcess();
                string executablePath          = proc.Modules[0].FileName;
                string executableFolder        = Path.GetDirectoryName(executablePath);
                string serviceExecutableFolder = Path.Combine(executableFolder, "CHTAgentService.exe");
                int    consecutiveFailures     = 0;
                int    consecutiveUpdates      = 0;

                var startTime   = DateTime.UtcNow;
                var serviceProc = Process.Start(serviceExecutableFolder);
                while (!WaitHandle.WaitAll(new WaitHandle[] { quitEvent }, 0))
                {
                    serviceProc.WaitForExit(10000);
                    if (serviceProc.HasExited)
                    {
                        var stopTime    = DateTime.UtcNow;
                        var processTime = stopTime - startTime;
                        int exitCode    = serviceProc.ExitCode;
                        logger.LogInfo("Service Executable Exit Code: {0}", exitCode);
                        if (exitCode == Constants.UPDATE_EXIT_CODE)
                        {
                            PerformUpdate();
                            if (processTime.TotalSeconds < UPTIME_THRESHOLD)
                            {
                                consecutiveUpdates++;
                            }
                            else
                            {
                                consecutiveUpdates = 0;
                            }
                        }
                        else if (exitCode != 0)
                        {
                            if (processTime.TotalSeconds < UPTIME_THRESHOLD)
                            {
                                consecutiveFailures++;
                            }
                            else
                            {
                                consecutiveFailures = 0;
                            }
                        }

                        bool delayStart = false;
                        if (consecutiveFailures > 5)
                        {
                            logger.LogError("{0} consecutive service process failures. Waiting for 30 seconds", consecutiveFailures);
                            delayStart = true;
                        }
                        else if (consecutiveUpdates > 5)
                        {
                            logger.LogError("{0} consecutive updates attempted. Waiting for 30 seconds", consecutiveUpdates);
                            delayStart = true;
                        }

                        if (delayStart)
                        {
                            WaitHandle.WaitAll(new WaitHandle[] { quitEvent }, 30000);
                        }

                        if (!WaitHandle.WaitAll(new WaitHandle[] { quitEvent }, 30000))
                        {
                            serviceProc = Process.Start(serviceExecutableFolder);
                        }
                    }
                }

                if (!serviceProc.HasExited)
                {
                    // TODO: Kill it with a signal
                    serviceProc.Kill();
                }
            }
            catch (FileNotFoundException e)
            {
                logger.LogError(String.Format("File Not Found: {0}", e.FileName));
            }
            catch (Exception e)
            {
                logger.LogError(e.ToString());
            }
        }
コード例 #13
0
        /// <summary>
        /// Saves a Triple Store to CSV Format
        /// </summary>
        /// <param name="store">Triple Store to save</param>
        /// <param name="parameters">A set of <see cref="StreamParams">StreamParams</see></param>
        public void Save(ITripleStore store, IStoreParams parameters)
        {
            ThreadedStoreWriterContext context = null;

            if (parameters is StreamParams)
            {
                //Create a new Writer Context
                context = new ThreadedStoreWriterContext(store, ((StreamParams)parameters).StreamWriter);
            }
            else if (parameters is TextWriterParams)
            {
                context = new ThreadedStoreWriterContext(store, ((TextWriterParams)parameters).TextWriter);
            }

            if (context != null)
            {
                //Check there's something to do
                if (context.Store.Graphs.Count == 0)
                {
                    context.Output.Close();
                    return;
                }

                //Queue the Graphs to be written
                foreach (IGraph g in context.Store.Graphs)
                {
                    context.Add(g.BaseUri);
                }

                //Start making the async calls
                List <IAsyncResult>  results = new List <IAsyncResult>();
                SaveGraphsDeletegate d       = new SaveGraphsDeletegate(this.SaveGraphs);
                for (int i = 0; i < this._threads; i++)
                {
                    results.Add(d.BeginInvoke(context, null, null));
                }

                //Wait for all the async calls to complete
                WaitHandle.WaitAll(results.Select(r => r.AsyncWaitHandle).ToArray());
                RdfThreadedOutputException outputEx = new RdfThreadedOutputException(WriterErrorMessages.ThreadedOutputFailure("CSV"));
                foreach (IAsyncResult result in results)
                {
                    try
                    {
                        d.EndInvoke(result);
                    }
                    catch (Exception ex)
                    {
                        outputEx.AddException(ex);
                    }
                }
                context.Output.Close();

                //If there were any errors we'll throw an RdfThreadedOutputException now
                if (outputEx.InnerExceptions.Any())
                {
                    throw outputEx;
                }
            }
            else
            {
                throw new RdfStorageException("Parameters for the CsvStoreWriter must be of the type StreamParams/TextWriterParams");
            }
        }
        public void FileSystemWatcher_File_Create_ForceLoopRestart(bool useExistingWatchers)
        {
            ExecuteWithRetry(() =>
            {
                FileSystemWatcher[] watchers  = new FileSystemWatcher[64];
                FileSystemWatcher[] watchers1 = new FileSystemWatcher[64];

                try
                {
                    string fileName = Path.Combine(TestDirectory, "file");
                    AutoResetEvent[] autoResetEvents = new AutoResetEvent[64];
                    for (var i = 0; i < watchers.Length; i++)
                    {
                        watchers[i]        = new FileSystemWatcher(TestDirectory);
                        watchers[i].Filter = Path.GetFileName(fileName);
                        autoResetEvents[i] = WatchCreated(watchers[i], new[] { fileName }).EventOccured;
                        watchers[i].EnableRaisingEvents = true;
                    }

                    File.Create(fileName).Dispose();
                    Assert.True(WaitHandle.WaitAll(autoResetEvents, WaitForExpectedEventTimeout_NoRetry));

                    File.Delete(fileName);
                    for (var i = 0; i < watchers.Length; i++)
                    {
                        watchers[i].EnableRaisingEvents = false;
                    }

                    File.Create(fileName).Dispose();
                    Assert.False(WaitHandle.WaitAll(autoResetEvents, WaitForUnexpectedEventTimeout));

                    File.Delete(fileName);

                    if (useExistingWatchers)
                    {
                        for (var i = 0; i < watchers.Length; i++)
                        {
                            watchers[i].EnableRaisingEvents = true;
                        }

                        File.Create(fileName).Dispose();
                        Assert.True(WaitHandle.WaitAll(autoResetEvents, WaitForExpectedEventTimeout_NoRetry));
                    }
                    else
                    {
                        AutoResetEvent[] autoResetEvents1 = new AutoResetEvent[64];
                        for (var i = 0; i < watchers1.Length; i++)
                        {
                            watchers1[i]        = new FileSystemWatcher(TestDirectory);
                            watchers1[i].Filter = Path.GetFileName(fileName);
                            autoResetEvents1[i] = WatchCreated(watchers1[i], new[] { fileName }).EventOccured;
                            watchers1[i].EnableRaisingEvents = true;
                        }

                        File.Create(fileName).Dispose();
                        Assert.True(WaitHandle.WaitAll(autoResetEvents1, WaitForExpectedEventTimeout_NoRetry));
                    }
                }
                finally
                {
                    for (var i = 0; i < watchers.Length; i++)
                    {
                        watchers[i]?.Dispose();
                        watchers1[i]?.Dispose();
                    }
                }
            });
        }
コード例 #15
0
        public override int DiscoverDynamicCategories()
        {
            var shows = new List <RssLink>();

            List <string> startLetterPages = new List <string>();
            string        data             = GetWebData(baseUrl);

            var startPage = GetWebData <HtmlDocument>(baseUrl);
            var baseUri   = new Uri(baseUrl);
            var letterDiv = startPage.DocumentNode.Descendants("div").FirstOrDefault(d => d.GetAttributeValue("class", "") == "multiGroupNavi multiGroupNaviAlpha");

            foreach (var li in letterDiv.Element("ul").Elements("li"))
            {
                var a = li.Element("a");
                if (a != null)
                {
                    startLetterPages.Add(a.GetAttributeValue("href", ""));
                }
            }

            var threadWaitHandles = new ManualResetEvent[startLetterPages.Count];

            for (int i = 0; i < startLetterPages.Count; i++)
            {
                threadWaitHandles[i] = new ManualResetEvent(false);
                new Thread(delegate(object o)
                {
                    int o_i = (int)o;

                    var showsPage = GetWebData <HtmlDocument>(new Uri(new Uri(baseUrl), startLetterPages[o_i]).AbsoluteUri);
                    var content   = showsPage.DocumentNode.Descendants("div").FirstOrDefault(d => d.GetAttributeValue("id", "") == "content");
                    foreach (var teaser in content.Descendants("div").Where(d => d.GetAttributeValue("class", "") == "innerTeaser"))
                    {
                        var imgSrc = teaser.Descendants("img").FirstOrDefault(img => img.GetAttributeValue("class", "") == "img").GetAttributeValue("src", "");
                        var a      = teaser.Descendants("a").FirstOrDefault().GetAttributeValue("href", "");

                        var infoDiv = teaser.Descendants("div").FirstOrDefault(d => d.GetAttributeValue("class", "") == "shortInfos");
                        var title   = infoDiv.Element("h4").InnerText;
                        var sub     = infoDiv.Element("p");

                        RssLink show = new RssLink()
                        {
                            Name        = HttpUtility.HtmlDecode(title.Trim()),
                            Thumb       = new Uri(new Uri(baseUrl), imgSrc).AbsoluteUri,
                            Url         = new Uri(new Uri(baseUrl), a).AbsoluteUri,
                            Description = (sub != null) ? HttpUtility.HtmlDecode(sub.InnerText) : ""
                        };
                        lock (show)
                            shows.Add(show);
                    }

                    threadWaitHandles[o_i].Set();
                })
                {
                    IsBackground = true
                }.Start(i);
            }
            WaitHandle.WaitAll(threadWaitHandles);

            Settings.Categories.Clear();
            shows.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
            shows.ForEach(show => Settings.Categories.Add(show));
            Settings.DynamicCategoriesDiscovered = true;
            return(Settings.Categories.Count);
        }
コード例 #16
0
        public static FractalGraph CalcFlame(double xCenter, double yCenter, double rDelta, long N,
                                             FlameFunction[] Functions, int Width, int Height, int Seed, int SuperSampling, double Gamma,
                                             double Vibrancy, bool Preview, bool Parallel, Variables Variables, ScriptNode Node,
                                             FractalZoomScript FractalZoomScript, object State)
        {
            double TotWeight = 0;
            double Weight;
            int    i, c = Functions.Length;
            Random Gen = new Random(Seed);

            if (c < 1)
            {
                throw new ScriptRuntimeException("At least one flame function needs to be provided.", Node);
            }

            if (SuperSampling < 1)
            {
                throw new ScriptRuntimeException("SuperSampling must be a postitive integer.", Node);
            }

            if (!Node.Expression.HandlesPreview)
            {
                Preview = false;
            }

            Array.Sort <FlameFunction>(Functions, (f1, f2) =>
            {
                double d = f2.Weight - f1.Weight;
                if (d < 0)
                {
                    return(-1);
                }
                else if (d > 0)
                {
                    return(1);
                }
                else
                {
                    return(0);
                }
            });

            double[]      SumWeights = new double[c];
            FlameFunction f;

            for (i = 0; i < c; i++)
            {
                f      = Functions[i];
                Weight = f.Weight;
                if (Weight < 0)
                {
                    throw new ScriptRuntimeException("Weights must be non-negative.", Node);
                }

                f.DefinitionDone();
                TotWeight    += Weight;
                SumWeights[i] = TotWeight;
            }

            if (TotWeight == 0)
            {
                throw new ScriptRuntimeException("The total weight of all functions must be postitive.", Node);
            }

            for (i = 0; i < c; i++)
            {
                SumWeights[i] /= TotWeight;
            }

            double AspectRatio = ((double)Width) / Height;
            double xMin, xMax, yMin, yMax;

            xMin = xCenter - rDelta / 2;
            xMax = xMin + rDelta;
            yMin = yCenter - rDelta / (2 * AspectRatio);
            yMax = yMin + rDelta / AspectRatio;

            int NrGames = Parallel ? System.Environment.ProcessorCount : 1;

            if (NrGames <= 1)
            {
                FlameState P = new FlameState(Gen, xMin, xMax, yMin, yMax, Width, Height, SuperSampling, N, ColorMode.Rgba, Node);
                Variables  v = new Variables();
                Variables.CopyTo(v);

                RunChaosGame(v, Functions, SumWeights, P, Preview, Gamma, Vibrancy, Node);

                return(new FractalGraph(P.RenderBitmapRgba(Gamma, Vibrancy, false, SKColors.White), xMin, yMin, xMax, yMax, rDelta,
                                        false, Node, FractalZoomScript, State));
            }
            else
            {
                FlameState[] P    = new FlameState[NrGames];
                WaitHandle[] Done = new WaitHandle[NrGames];
                Thread[]     T    = new Thread[NrGames];

                try
                {
                    for (i = 0; i < NrGames; i++)
                    {
                        Done[i] = new ManualResetEvent(false);
                        P[i]    = new FlameState(Gen, xMin, xMax, yMin, yMax, Width, Height, SuperSampling,
                                                 i < NrGames - 1 ? N / NrGames : N - (N / NrGames) * (NrGames - 1),
                                                 ColorMode.Rgba, Node);

                        Variables v = new Variables();
                        Variables.CopyTo(v);

                        T[i] = new Thread(new ParameterizedThreadStart(ChaosGameThread))
                        {
                            Name     = "FlameFractal thread #" + (i + 1).ToString(),
                            Priority = ThreadPriority.BelowNormal
                        };

                        T[i].Start(new object[] { Done[i], i, v, Functions, SumWeights, P[i],
                                                  Node, i == 0 ? Preview : false, Gamma, Vibrancy });
                    }

                    WaitHandle.WaitAll(Done);

                    for (i = 1; i < NrGames; i++)
                    {
                        P[0].Add(P[i]);
                    }

                    return(new FractalGraph(P[0].RenderBitmapRgba(Gamma, Vibrancy, false, SKColors.White), xMin, yMin, xMax, yMax, rDelta,
                                            false, Node, FractalZoomScript, State));
                }
                catch (ThreadAbortException)
                {
                    for (i = 0; i < NrGames; i++)
                    {
                        try
                        {
                            if (T[i] is null)
                            {
                                continue;
                            }

                            if (Done[i] is null || !Done[i].WaitOne(0))
                            {
                                T[i].Abort();
                            }
                        }
                        catch (Exception)
                        {
                            // Ignore
                        }
                    }

                    return(null);
                }
                finally
                {
                    for (i = 0; i < NrGames; i++)
                    {
                        try
                        {
                            if (Done[i] != null)
                            {
                                Done[i].Close();
                            }
                        }
                        catch (Exception)
                        {
                            // Ignore
                        }
                    }
                }
            }
        }
コード例 #17
0
        public override void Variables(Response response, dynamic args)
        {
            int reference = getInt(args, "variablesReference", -1);

            if (reference == -1)
            {
                SendErrorResponse(response, 3009, "variables: property 'variablesReference' is missing", null, false, true);
                return;
            }

            WaitForSuspend();
            var variables = new List <Variable>();

            ObjectValue[] children;
            if (_variableHandles.TryGet(reference, out children))
            {
                if (children != null && children.Length > 0)
                {
                    bool more = false;
                    if (children.Length > MAX_CHILDREN)
                    {
                        children = children.Take(MAX_CHILDREN).ToArray();
                        more     = true;
                    }

                    if (children.Length < 20)
                    {
                        // Wait for all values at once.
                        WaitHandle.WaitAll(children.Select(x => x.WaitHandle).ToArray());
                        foreach (var v in children)
                        {
                            try
                            {
                                variables.Add(CreateVariable(v));
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    else
                    {
                        foreach (var v in children)
                        {
                            v.WaitHandle.WaitOne();
                            try
                            {
                                variables.Add(CreateVariable(v));
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }

                    if (more)
                    {
                        variables.Add(new Variable("...", null, null));
                    }
                }
            }

            SendResponse(response, new VariablesResponseBody(variables));
        }
コード例 #18
0
ファイル: BuildManager.cs プロジェクト: Skycweb/mono-skycweb
 public void Dispose()
 {
     WaitHandle.WaitAll(submissions.Select(s => s.WaitHandle).ToArray());
     BuildNodeManager.Stop();
 }
コード例 #19
0
 protected override void OnStop()
 {
     _cancellationTokenSource.Cancel();
     WaitHandle.WaitAll(ResetEvents.Select(e => e as WaitHandle).ToArray(), 3000);
     Log.Instance.Info("Windows service stoped");
 }
コード例 #20
0
        static void Main(string[] args)
        {
            FuncForm myForm  = new FuncForm();
            Chart    myChart = myForm.chart1;

            Console.WriteLine("Нахождение площади функций вида y = ax^3 + bx^2 + cx + d методом Монте-Карло.");
            Console.Write("Введите а: "); if (!Double.TryParse(Console.ReadLine(), out a))
            {
                a = 0;
            }
            Console.Write("Введите b: "); if (!Double.TryParse(Console.ReadLine(), out b))
            {
                b = 0;
            }
            Console.Write("Введите c: "); if (!Double.TryParse(Console.ReadLine(), out c))
            {
                c = 0;
            }
            Console.Write("Введите d: "); if (!Double.TryParse(Console.ReadLine(), out d))
            {
                d = 0;
            }

            if (a == b && b == c && c == d && d == 0)
            {
                Console.WriteLine("Нечего искать. Нажмите любую кнопку, чтобы выйти.");
                Console.ReadKey();
                return;
            }
            Console.WriteLine("На каком отрезке искать площадь?");
            Console.Write("X1: "); if (!Int32.TryParse(Console.ReadLine(), out x1))
            {
                x1 = new Random().Next(-10, 5);
            }
            Console.Write("X2: "); if (!Int32.TryParse(Console.ReadLine(), out x2) || x2 < x1)
            {
                x2 = new Random().Next(x1, x1 + 5);
            }

            int inter;

            for (int i = x1; i <= x2; i++)           // Находим верхнюю и нижнюю границы
            {
                inter = (int)getFuncPoint(i);
                myChart.Series[0].Points.AddXY(i, inter);
                if (y1 > inter)
                {
                    y1 = inter;
                }
                else if (y2 < inter)
                {
                    y2 = inter;
                }
            }
            if (y1 > 0)
            {
                y1 = 0;
            }
            if (y2 < 0)
            {
                y2 = 0;
            }

            Console.Write("Сколько раз смоделируется расчет (чем больше, тем точнее): ");
            int threadCount;

            if (!int.TryParse(Console.ReadLine(), out threadCount) || threadCount < 1)
            {
                threadCount = new Random().Next(1, 3);
                Console.WriteLine("Принятое число расчетов: " + threadCount);
            }
            else if (threadCount > 64)              // Делим задачи между потоками
            {
                part        = threadCount / 64;
                balance     = threadCount % 64;
                threadCount = 64;
            }

            Console.Write("Сколько точек: ");
            int pointNumber;

            if (!int.TryParse(Console.ReadLine(), out pointNumber) || pointNumber < 1)
            {
                pointNumber = new Random().Next(15000, 45000);
                Console.WriteLine("Принятое число точек: " + pointNumber);
            }


            for (int i = 0; i < threadCount; i++)
            {
                EventWaitHandle handle = new AutoResetEvent(false);
                new Thread(delegate() { MonteCarloMethod(pointNumber, handle, (i < balance ? i + 1 : i)); }).Start();
                handles.Add(handle);
            }
            WaitHandle.WaitAll(handles.ToArray());

            myChart.Series[0].BorderWidth = 3;
            myChart.Series.Add("Bounds");
            myChart.Series[1].Points.AddXY(x2, 0);
            myChart.Series[1].Points.AddXY(x1, 0);
            myChart.Series.Add("Area = " + areaList.Average()).Color = System.Drawing.Color.DarkBlue;

            Application.Run(myForm);

            Console.WriteLine("Нажмите любую кнопку, чтобы выйти.");
            Console.ReadLine();
        }
コード例 #21
0
 /// <summary>
 /// Waits for all the elements in the specified array to receive a signal.
 /// </summary>
 /// <returns>Waits for all the elements in the specified array to receive a signal.</returns>
 public static bool WaitAll()
 {
     return(WaitHandle.WaitAll(AutoResetEvents.ToArray()));
 }
コード例 #22
0
        /// <summary>
        /// Console application entry point.
        /// </summary>
        /// <param name="args">An array of arguments.</param>
        /// <returns>Zero (0) for success and non-zero for failure.</returns>
        public static int Main(string[] args)
        {
            double    spinCycle  = Constants.MinSpinTimeout;
            bool      forceWrite = false;
            Installer installer;
            Spinner   spin = new Spinner();

            try
            {
                string configPath = string.Empty;

                // Retain backwards compatability with using just config file as a single parameter.
                if (args.Length > 0 && !args[0].StartsWith("/", StringComparison.OrdinalIgnoreCase))
                {
                    configPath = args[0];
                    if (!File.Exists(configPath))
                    {
                        forceWrite = true;
                    }
                }
                else
                {
                    configPath = Path.Combine(Directory.GetCurrentDirectory(), Constants.SQLInstallerXml);
                }

                // Allow parameter overrides and/or specifying all parameters from command line.
                Arguments <Parameters> parms = null;
                if (File.Exists(configPath))
                {
                    parms = new Arguments <Parameters>(args, Parameters.Load(configPath));
                }
                else
                {
                    parms = new Arguments <Parameters>(args, new Parameters(configPath));
                }

                if (!parms.IsValid)
                {
                    throw new ApplicationException(parms.ValidationErrors);
                }

                if (parms.Instance.WriteConfig || forceWrite)
                {
                    if (!parms.Instance.IsProtected)
                    {
                        parms.Instance.ProtectConnectionString();
                    }
                    else
                    {
                        parms.Instance.Write();
                    }
                }

                spin.Start(spinCycle);
                Console.WriteLine(Resources.StatusConnecting);

                installer = new Installer(parms.Instance);
                installer.Prepare();
                spin.Stop();

                if (installer.Exists && !parms.Instance.Options.Has(Options.Drop))
                {
                    if (installer.IsCurrent && !parms.Instance.Options.Has(Options.Retry))
                    {
                        Console.WriteLine(parms.Instance.Database + Resources.StatusAlreadyUpgraded + installer.Version + Resources.StatusBy + installer.UpgradeBy);
                        return(0);
                    }
                    else
                    {
                        if (!parms.Instance.NoPrompt)
                        {
                            ConsoleKey key = ConsoleKey.NoName;
                            while (key != ConsoleKey.N && key != ConsoleKey.Y)
                            {
                                Console.WriteLine();
                                Console.Write(Resources.AskUpgrade + parms.Instance.Database + Resources.AskToVersion + installer.Upgrade + Resources.AskYesNo);
                                key = Console.ReadKey(true).Key;
                            }

                            Console.WriteLine(key);
                            if (key == ConsoleKey.N)
                            {
                                return(0);
                            }
                        }
                    }
                }

                InstallMethod im = new InstallMethod(installer.Create);
                AsyncCallback cb = new AsyncCallback(InstallCallback);

                IAsyncResult asyncResult = im.BeginInvoke(cb, im);

                WaitHandle[] bg   = new WaitHandle[] { asyncResult.AsyncWaitHandle };
                Progress     prog = new Progress(StatusMessage.Running);
                while (prog.Status != StatusMessage.Exit)
                {
                    prog = installer.GetProgress(!WaitHandle.WaitAll(bg, 100, true));
                    switch (prog.Status)
                    {
                    case StatusMessage.Start:
                        Console.WriteLine(prog.Message + Constants.Wait);
                        spin.Start(spinCycle);
                        break;

                    case StatusMessage.Detail:
                        spin.Stop();
                        Console.WriteLine(prog.Message);
                        spin.Start(spinCycle);
                        break;

                    case StatusMessage.Exit:
                        spin.Stop();
                        Console.WriteLine(Resources.StatusCompletedWith + prog.Percent + Resources.StatusErrorCount);
                        break;

                    case StatusMessage.Complete:
                    case StatusMessage.Running:
                    case StatusMessage.Progress:
                    default:
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format(Resources.ErrorGeneric, ex.Message));
            }
            finally
            {
                if (spin != null)
                {
                    spin.Stop();
                }
            }

            return(0);
        }
コード例 #23
0
        public void ThreadTaskComparison()
        {
            Stopwatch watch = new Stopwatch();
            //64 is upper limit for WaitHandle.WaitAll() method
            int maxWaitHandleWaitAllAllowed = 64;

            ManualResetEventSlim[] mres =
                new ManualResetEventSlim[maxWaitHandleWaitAllAllowed];

            for (int i = 0; i < mres.Length; i++)
            {
                mres[i] = new ManualResetEventSlim(false);
            }

            long threadTime = 0;
            long taskTime   = 0;

            watch.Start();

            //start a new classic Thread and signal the ManualResetEvent when its done
            //so that we can snapshot time taken, and

            for (int i = 0; i < mres.Length; i++)
            {
                int    idx = i;
                Thread t   = new Thread((state) =>
                {
                    for (int j = 0; j < 10; j++)
                    {
                        Console.WriteLine(string.Format("{0}:, outputing {1}",
                                                        state.ToString(), j.ToString()));
                    }

                    // Signal each event
                    mres[idx].Set();
                });

                t.Start(string.Format("Thread{0}", i.ToString()));
            }

            // WaitHandle.WaitAll((from x in mres select x.WaitHandle).ToArray());
            WaitHandle.WaitAll((mres.Select((x) => x.WaitHandle).ToArray()));

            threadTime = watch.ElapsedMilliseconds;
            watch.Reset();

            for (int i = 0; i < mres.Length; i++)
            {
                mres[i].Reset();
            }

            watch.Start();

            for (int i = 0; i < mres.Length; i++)
            {
                int idx = i;

                // Notice the two args passed to StartNew()
                Task task = Task.Factory.StartNew((state) =>
                {
                    for (int j = 0; j < 10; j++)
                    {
                        Console.WriteLine(string.Format("{0}:, outputing {1}",
                                                        state.ToString(), j.ToString()));
                    }
                    mres[idx].Set();
                }, string.Format("Task{0}", i.ToString()));
            }

            WaitHandle.WaitAll((from x in mres select x.WaitHandle).ToArray());

            taskTime = watch.ElapsedMilliseconds;
            Console.WriteLine("Thread Time waited : {0}ms", threadTime);
            Console.WriteLine("Task Time waited : {0}ms", taskTime);

            for (int i = 0; i < mres.Length; i++)
            {
                mres[i].Dispose();
            }

            Console.WriteLine("All done, press Enter to Quit");
            Console.ReadLine();
        }
コード例 #24
0
        private void Handshake(EncryptionTypes encryptionA, EncryptionTypes encryptionB, bool addInitial)
        {
            bool doneA = false;
            bool doneB = false;

            HandshakeMessage m = new HandshakeMessage(rig.Torrent.InfoHash, "12345123451234512345", VersionInfo.ProtocolStringV100);

            byte[] handshake = m.Encode();

            PeerAEncryption a = new PeerAEncryption(rig.Torrent.InfoHash, encryptionA);

            if (addInitial)
            {
                a.AddPayload(handshake);
            }

            PeerBEncryption b = new PeerBEncryption(new InfoHash[] { rig.Torrent.InfoHash }, encryptionB);

            IAsyncResult resultA = a.BeginHandshake(conn.Outgoing, null, null);
            IAsyncResult resultB = b.BeginHandshake(conn.Incoming, null, null);

            WaitHandle[] handles = new WaitHandle[] { resultA.AsyncWaitHandle, resultB.AsyncWaitHandle };
            int          count   = 1000;

            while (!WaitHandle.WaitAll(handles, 5, true))
            {
                if (!doneA && (doneA = resultA.IsCompleted))
                {
                    a.EndHandshake(resultA);
                }
                if (!doneB && (doneB = resultB.IsCompleted))
                {
                    b.EndHandshake(resultB);
                }

                if (count-- == 0)
                {
                    Assert.Fail("Could not handshake");
                }
            }
            if (!doneA)
            {
                a.EndHandshake(resultA);
            }
            if (!doneB)
            {
                b.EndHandshake(resultB);
            }

            HandshakeMessage d = new HandshakeMessage();

            if (!addInitial)
            {
                a.Encrypt(handshake, 0, handshake.Length);
                b.Decrypt(handshake, 0, handshake.Length);
                d.Decode(handshake, 0, handshake.Length);
            }
            else
            {
                d.Decode(b.InitialData, 0, b.InitialData.Length);
            }
            Assert.AreEqual(m, d);


            if (encryptionA == EncryptionTypes.RC4Full || encryptionB == EncryptionTypes.RC4Full)
            {
                Assert.IsTrue(a.Encryptor is RC4);
                Assert.IsTrue(b.Encryptor is RC4);
            }
            else if (encryptionA == EncryptionTypes.RC4Header || encryptionB == EncryptionTypes.RC4Header)
            {
                Assert.IsTrue(a.Encryptor is RC4Header);
                Assert.IsTrue(b.Encryptor is RC4Header);
            }
            else if (encryptionA == EncryptionTypes.PlainText || encryptionB == EncryptionTypes.PlainText)
            {
                Assert.IsTrue(a.Encryptor is PlainTextEncryption);
                Assert.IsTrue(b.Encryptor is PlainTextEncryption);
            }
        }
コード例 #25
0
        internal static void UpdateAssemblies()
        {
            var assembliesToUpdate = GetAssembliesToBeUpdated();

            if (assembliesToUpdate.Count == 0)
            {
                return;
            }

            if (!WaitForVCSServerConnection(true))
            {
                assembliesToUpdate.Clear();
                return;
            }

            var assemblyPaths = assembliesToUpdate.Select(c => c.Path);

            if (Provider.enabled && !APIUpdaterHelper.CheckoutAndValidateVCSFiles(assemblyPaths))
            {
                assembliesToUpdate.Clear();
                return;
            }

            var sw           = Stopwatch.StartNew();
            var updatedCount = 0;

            var assembliesToCheckCount = assembliesToUpdate.Count;
            var tasks = assembliesToUpdate.Select(a => new AssemblyUpdaterUpdateTask(a)).ToArray();

            foreach (var task in tasks)
            {
                CollectAssemblyObsoleteAPIUsage(task.Candidate.Path);
                ThreadPool.QueueUserWorkItem(RunAssemblyUpdaterTask, task);
            }

            var finishOk   = false;
            var waitEvents = tasks.Select(t => t.Event).ToArray();
            var timeout    = TimeSpan.FromSeconds(30);

            if (WaitHandle.WaitAll(waitEvents, timeout))
            {
                if (!HandleAssemblyUpdaterErrors(tasks))
                {
                    updatedCount = ProcessSuccessfulUpdates(tasks);
                    finishOk     = true;
                }
            }
            else
            {
                LogTimeoutError(tasks);
            }

            sw.Stop();
            APIUpdaterLogger.WriteToFile(L10n.Tr("Update finished with {0} in {1} ms ({2}/{3} assemblie(s) updated)."), finishOk ? L10n.Tr("success") : L10n.Tr("error"), sw.ElapsedMilliseconds, updatedCount, assembliesToCheckCount);

            if (updatedCount > 0 && !EditorCompilationInterface.Instance.DoesProjectFolderHaveAnyScripts())
            {
                ReportPossibleUpdateFinished(false);
            }

            PersistListOfAssembliesToUpdate();
        }
コード例 #26
0
        public static void Main()
        {
            // Subscribe system log off/shutdown or application close events
            SystemEvents.SessionEnding
                += new SessionEndingEventHandler(ShutdownEventHandler);
            AppDomain.CurrentDomain.ProcessExit
                += new EventHandler(ShutdownEventHandler);

            // Initialize objects for main thread
            try
            {
                coreControl = DiReCTCore.getInstance();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("Thread resource creation failed.");
                CleanupExit();
            }

            // Initialize objects for threads
            // Initialize thread objects and control data block of each modules
            try
            {
                ModuleThreadHandles
                    = new Thread[(int)ModuleThread.NumberOfModules];
                ModuleControlDataBlocks = new ModuleControlDataBlock[
                    (int)ModuleThread.NumberOfModules];
                ModuleReadyEvents = new AutoResetEvent[
                    (int)ModuleThread.NumberOfModules];
                ModuleInitFailedEvents = new AutoResetEvent[
                    (int)ModuleThread.NumberOfModules];
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("Thread resource creation failed.");
                CleanupExit();
            }

            // AAA Module
            try
            {
                // Create and intialize AAA module
                ModuleThreadHandles[(int)ModuleThread.AAA]
                    = new Thread(AAAModule.AAAInit);
                ModuleControlDataBlocks[(int)ModuleThread.AAA]
                    = new ModuleControlDataBlock();
                ModuleThreadHandles[(int)ModuleThread.AAA]
                .Start(ModuleControlDataBlocks[(int)ModuleThread.AAA]);
            }
            catch (ArgumentNullException ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("AAA module thread creation failed.");
                CleanupExit();
            }

            // DM Module
            try
            {
                // Create and intialize DM module
                ModuleThreadHandles[(int)ModuleThread.DM]
                    = new Thread(DMModule.DMInit);
                ModuleControlDataBlocks[(int)ModuleThread.DM]
                    = new ModuleControlDataBlock();
                ModuleThreadHandles[(int)ModuleThread.DM]
                .Start(ModuleControlDataBlocks[(int)ModuleThread.DM]);
            }
            catch (ArgumentNullException ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("DM module thread creation failed.");
                CleanupExit();
            }

            // DS Module
            try
            {
                // Create and intialize DS module
                ModuleThreadHandles[(int)ModuleThread.DS]
                    = new Thread(DSModule.DSInit);
                ModuleControlDataBlocks[(int)ModuleThread.DS]
                    = new ModuleControlDataBlock();
                ModuleThreadHandles[(int)ModuleThread.DS]
                .Start(ModuleControlDataBlocks[(int)ModuleThread.DS]);
            }
            catch (ArgumentNullException ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("DS module thread creation failed.");
                CleanupExit();
            }

            // MAN Module
            try
            {
                // Create and intialize MAN module
                ModuleThreadHandles[(int)ModuleThread.MAN]
                    = new Thread(MANModule.MANInit);
                ModuleControlDataBlocks[(int)ModuleThread.MAN]
                    = new ModuleControlDataBlock();
                ModuleThreadHandles[(int)ModuleThread.MAN]
                .Start(ModuleControlDataBlocks[(int)ModuleThread.MAN]);
            }
            catch (ArgumentNullException ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("MAN module thread creation failed.");
                CleanupExit();
            }

            // RTQC Module
            try
            {
                // Create and intialize RTQC module
                ModuleThreadHandles[(int)ModuleThread.RTQC]
                    = new Thread(RTQCModule.RTQCInit);
                ModuleControlDataBlocks[(int)ModuleThread.RTQC]
                    = new ModuleControlDataBlock();
                ModuleThreadHandles[(int)ModuleThread.RTQC]
                .Start(ModuleControlDataBlocks[(int)ModuleThread.RTQC]);
            }
            catch (ArgumentNullException ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("RTQC module thread creation failed.");
                CleanupExit();
            }

            // Initialize the thread object of GUI thread
            try
            {
                UIThreadHandle = new Thread(UIMainFunction);
                UIThreadHandle.SetApartmentState(ApartmentState.STA);
            }
            catch (ArgumentNullException ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("UI thread creation failed.");
                CleanupExit();
            }

            // Set the array of events for waiting signals raised by
            // modules using WaitAll and WaitAny below
            for (int i = 0; i < (int)ModuleThread.NumberOfModules; i++)
            {
                ModuleReadyEvents[i]
                    = ModuleControlDataBlocks[i].ThreadParameters
                      .ModuleReadyEvent;

                ModuleInitFailedEvents[i]
                    = ModuleControlDataBlocks[i].ThreadParameters
                      .ModuleInitFailedEvent;
            }

            while (InitHasFailed == false)
            {
                if (WaitHandle.WaitAll(ModuleReadyEvents,
                                       (int)TimeInterval.LongTime,
                                       true))
                {
                    Debug.WriteLine(
                        "Phase 1 initialization of all modules complete!");
                    break;
                }
                else
                {
                    int WaitReturnValue
                        = WaitHandle.WaitAny(ModuleInitFailedEvents,
                                             (int)TimeInterval.VeryVeryShortTime,
                                             true);
                    if (WaitReturnValue != WaitHandle.WaitTimeout)
                    {
                        InitHasFailed = true;
                        CleanupExit();
                    }
                }
            }
            Debug.WriteLine("Core Thread ID: " + Thread.CurrentThread.ManagedThreadId);
            // Signal modules to start working
            ModuleStartWorkEvent.Set();

            // Start to execute UI
            try
            {
                UIThreadHandle.Start();
            }
            catch (ArgumentNullException ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("UI thread can not start!");
                CleanupExit();
            }

            coreControl.Run();
            UIThreadHandle.Join();
            CleanupExit();
            //return;
        }
コード例 #27
0
        //[DllImport("Kernel32.dll")]
        //static extern bool QueryPerformanceCounter(out long lpPerformanceCount);


        /// <summary>
        /// A general parallel section;
        /// runs <paramref name="operation"/> in parallel, with <see cref="NumThreads"/> number of threads;
        /// </summary>
        /// <param name="operation">operation to perform in parallel</param>
        /// <remarks>
        /// if at least one thread throws an exception, an exception it hrown.
        /// </remarks>
        public static void Run(RunParallel operation)
        {
            //long start;
            //QueryPerformanceCounter(out start);


            if (m_CurrentWorker != null)
            {
                throw new ApplicationException("already in parallel section");
            }

            m_CurrentWorker = operation;
            int N = NumThreads;

            if (m_sync == null || m_sync.Length != (N - 1))
            {
                m_sync = new ManualResetEvent[N - 1];
                m_exc  = new Exception[N];
                //ThreadRuntime = new long[N];
            }
            for (int i = 0; i < N - 1; i++)
            {
                m_sync[i] = new ManualResetEvent(false);
                m_exc[i]  = null;
            }

            //System.Threading.ThreadPool.SetMinThreads(N-1, 0);
            //System.Threading.ThreadPool.SetMaxThreads(N-1, 0);
            for (int i = 1; i < N; i++)
            {
                System.Threading.ThreadPool.QueueUserWorkItem(Worker, new int[] { i, N });
            }

            try {
                Worker(new int[] { 0, N }); // run the 0-th pice of work in the current thread !
            } catch (Exception _e) {
                m_exc[0] = _e;
            }
            //long sync_st;
            //QueryPerformanceCounter(out sync_st);
            if (N > 1)
            {
                WaitHandle.WaitAll(m_sync);
            }
            //long sync_end;
            //QueryPerformanceCounter(out sync_end);

            m_CurrentWorker = null;
            for (int i = 0; i < N; i++)
            {
                if (m_exc[i] != null)
                {
                    throw new ApplicationException("at least one thread (" + i + " of " + N + " throwed an exception;", m_exc[i]);
                }
            }

            //long end;
            //QueryPerformanceCounter(out end);
            //{
            //    long runtime = end - start;
            //    long synctime = sync_end - sync_st;
            //    double perc = (double)synctime / (double)runtime;
            //    Console.WriteLine(N + " thr, total runtime: " + runtime + ", synctime: " + synctime + " = " + perc);

            //    /*for (int i = 0; i < N; i++) {
            //        Console.Write("thread #");
            //        Console.Write(i);
            //        Console.Write(": ");
            //        Console.Write(ThreadRuntime[i]);
            //        double perc = (double)ThreadRuntime[i] / (double)runtime;
            //        Console.Write(", = ");
            //        Console.Write(perc);
            //        Console.Write(" of total.");
            //        Console.WriteLine();
            //    }*/
            //}
        }
コード例 #28
0
 protected override void OnStop()
 {
     _cts.Cancel();
     WaitHandle.WaitAll(new WaitHandle[] { _createWorkerDone, _deleteWorkerDone }, TimeSpan.FromMilliseconds(ServiceShutdownTimeoutMs));
 }
コード例 #29
0
        /// <summary>
        /// 获取指定日期区间的日运营报表数据。
        /// </summary>
        /// <param name="queryType">查询类型 0:按时间查询 1:按日期查询。</param>
        /// <param name="start_time">开始时间  2012-05-12。</param>
        /// <param name="end_time">结束时间 2012-05-13。</param>
        /// <param name="shiftName">班别。</param>
        /// <param name="roomName">车间名称。</param>
        /// <param name="proModel">产品型号。</param>
        /// <param name="partNumber">产品料号。</param>
        /// <param name="proId">产品ID号。</param>
        /// <param name="workOrderNo">工单号。</param>
        /// <returns>包含日运营报表数据的数据集。</returns>
        public DataSet GetDailyReportData(
            int queryType,
            string start_time,
            string end_time,
            string shiftName,
            string roomName,
            string proModel,
            string proId,
            string partNumber,
            string workOrderNo,
            string factoryshift)
        {
            string[] storeProcedures = new string[] {
                "SP_QRY_DAILY_REPORT_DATA_TOP",
                "SP_QRY_DAILY_REPORT_DATA_OUT",
                "SP_QRY_DAILY_REPORT_DATA_WAREHOUSE_FACT",
                "SP_QRY_DAILY_REPORT_DATA_WAREHOUSE_REWORK",
                "SP_QRY_DAILY_REPORT_DATA_WIP",
                "SP_QRY_DAILY_REPORT_DATA_BRACKET",
                "SP_QRY_DAILY_REPORT_DATA_CHECK",
                "SP_QRY_DAILY_REPORT_DATA_CTM",
                "SP_QRY_DAILY_REPORT_DATA_FRAG"
            };

            dicDailyReportDatas = new Dictionary <string, DataTable>();
            dicAutoEvents       = new Dictionary <string, AutoResetEvent>();

            using (DbConnection con = this._db.CreateConnection())
            {
                foreach (string storeProcedure in storeProcedures)
                {
                    AutoResetEvent autoEvent = new AutoResetEvent(false);
                    dicAutoEvents.Add(storeProcedure, autoEvent);

                    DbCommand cmd = con.CreateCommand();
                    cmd.CommandType    = CommandType.StoredProcedure;
                    cmd.CommandText    = storeProcedure;
                    cmd.CommandTimeout = 120;
                    this._db.AddInParameter(cmd, "p_query_type", DbType.Decimal, queryType);
                    this._db.AddInParameter(cmd, "p_start_date", DbType.String, start_time);
                    this._db.AddInParameter(cmd, "p_end_date", DbType.String, end_time);
                    this._db.AddInParameter(cmd, "p_shiftName", DbType.String, shiftName);
                    this._db.AddInParameter(cmd, "p_roomName", DbType.String, roomName);
                    this._db.AddInParameter(cmd, "p_proModel", DbType.String, proModel);
                    this._db.AddInParameter(cmd, "p_proId", DbType.String, proId);
                    this._db.AddInParameter(cmd, "p_partNumber", DbType.String, partNumber);
                    this._db.AddInParameter(cmd, "p_workOrder", DbType.String, workOrderNo);
                    this._db.AddInParameter(cmd, "p_factoryshift", DbType.String, factoryshift);
                    ParameterizedThreadStart start = new ParameterizedThreadStart(ExecuteStoreProcedure);
                    Thread t = new Thread(start);
                    t.Start(cmd);
                }
            }
            WaitHandle.WaitAll(dicAutoEvents.Values.ToArray());
            dicAutoEvents.Clear();
            dicAutoEvents = null;

            DataSet dsReturn = new DataSet();

            foreach (DataTable dt in dicDailyReportDatas.Values)
            {
                dsReturn.Merge(dt);
            }
            dicDailyReportDatas.Clear();
            dicDailyReportDatas = null;
            return(dsReturn);
        }
コード例 #30
0
ファイル: Task.cs プロジェクト: netmatze/ParallelLib
 public void Wait()
 {
     WaitHandle.WaitAll(waitHandles);
 }