Example #1
0
        public DfekmProcessor(Guid id, Int32 myId, Uri librarian, Int32 clusterCount, Task[] problemData, Int32 start, Int32 len, IDistanceAlgorithm<Task> alg)
        {
            // Initialize stuff
            this._id = id;
            this._myId = myId;
            this._problemData = problemData;
            this._processorData = new ArraySegment<Task>(_problemData, start, len);
            this._distanceAlg = alg;

            // Initialize WCF librarian proxy
            EndpointAddress endpoint = new EndpointAddress(librarian);
            _librarian = ChannelFactory<ILibrarianService>.CreateChannel(new BasicHttpBinding(), endpoint);
            _librarian.InitializeKMeans(id);

            // Check if this is node-zero
            if (myId == 0)
            {
                // Grab a random sample
                Int32 sampleSize = (Int32)Math.Ceiling(Math.Sqrt(_problemData.Length));
                if (sampleSize < clusterCount) sampleSize = clusterCount;

                Task[] sample = _problemData.OrderBy((Task t) => { return rand.Next(); }).Take(sampleSize).ToArray();

                // Run k-medoid on the sample

                // Create the first row of CA Table

            }
        }
Example #2
0
	public void BeginListen()
	{
		listenCancel = new CancellationTokenSource();
		var token = listenCancel.Token;
		listeners = _proxies.Select(proxy =>
		{
			return Task.Factory.StartNew(() =>
			{
				while (!token.IsCancellationRequested)
				{
					var t = proxy.ReceiveAsync();
					t.Wait();
					_routedDatas.Enqueue(t.Result);
				}
			}, token);
		}).ToArray();
		dataHandler = Task.Factory.StartNew(() =>
		{
			while (!token.IsCancellationRequested)
			{
				JObject data;
				if (_routedDatas.TryDequeue(out data))
				{
					Task[] ts = null;
					lock (_sigLock)
					{
						ts = _signals.Values.Select(row => row.HandleCall(data)).ToArray();
					}
					Task.WaitAll(ts);
				}
			}
		});
	}
Example #3
0
        public Form1()
        {
            glmanager = new GLManager();

            InitializeComponent();
            glmanager.SetGL(this.openGLCtrl1.OpenGL);
            cycleTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
            cycleTimer.Interval = 1;
            opTimer.Elapsed += new ElapsedEventHandler(OpTimeEvent);
            opTimer.Interval = 1000;

            for (int d = 0; d < blockCountZ; d++)
            {
                for (int w = 0; w < blockCountX; w++)
                {
                    for (int h = 0; h < blockCountY; h++)
                    {
                        managers.Add(new WorkManager(blockWidth, blockHeight, blockDepth, w, h, d, glmanager));
                    }
                }
            }

            taskArray = new Task[managers.Count];

            cycleTimer.Start();
            opTimer.Start();
        }
Example #4
0
 private TaskRunner(BlockingCollection<Task> queue, Task[] tasks, CancellationTokenSource cancellationTokenSource, Action<string> logger)
 {
     _queue = queue;
     _tasks = tasks;
     _cancellationTokenSource = cancellationTokenSource;
     _logger = logger;
 }
	private void CleanUp()
	{
		_currentQueue = null;
		_consumerTasks = null;
		_producerTasks = null;
		_cancelSource = null;
	}
Example #6
0
        public void Run(string connectionString, string hubName, string measureNameFilter)
        {
            NamespaceManager nsmgr = NamespaceManager.CreateFromConnectionString(connectionString);
            EventHubDescription desc = nsmgr.GetEventHub(hubName);

            string consumerGroupName = _consumerGroupPrefix + DateTime.UtcNow.Ticks.ToString();
            ConsumerGroupDescription consumerGroupDesc = nsmgr.CreateConsumerGroupIfNotExists(new ConsumerGroupDescription(hubName, consumerGroupName));

            EventHubClient client = EventHubClient.CreateFromConnectionString(connectionString, hubName);

            int numPartitions = desc.PartitionCount;
            _receivers = new EventHubReceiver[numPartitions];
            //_receiversLastUpdate = new DateTime[numPartitions];
            //for (int i = 0; i < numPartitions; i++)
            //{
            //    _receiversLastUpdate[i] = DateTime.UtcNow;
            //}

            _tasks = new Task[numPartitions];
            _buffers = new Dictionary<string, CircularBuffer<SensorDataContract>>();
            _measureNameFilter = measureNameFilter;

            for (int iPart = 0; iPart < desc.PartitionCount; iPart++)
            {
                EventHubReceiver receiver = client.GetConsumerGroup(consumerGroupName).CreateReceiver(
                    desc.PartitionIds[iPart], DateTime.UtcNow - TimeSpan.FromMinutes(2));
                _receivers[iPart] = receiver;

                Task<IEnumerable<EventData>> task = receiver.ReceiveAsync(1000, TimeSpan.FromSeconds(1));

                int thisPart = iPart;
                task.ContinueWith(new Action<Task<IEnumerable<EventData>>>((t) => OnTaskComplete(t, thisPart)));
                _tasks[iPart] = task;
            }
        }
        protected override ZingerResult IterativeSearchStateSpace()
        {
            //outer loop to search the state space Iteratively
            do
            {
                //Increment the iterative bound
                ZingerConfiguration.zBoundedSearch.IncrementIterativeBound();

                //call the frontier reset function
                GLobalFrontierSet.StartOfIterationReset();

                try
                {
                    searchWorkers = new Task[ZingerConfiguration.DegreeOfParallelism];
                    //create parallel search threads
                    for (int i = 0; i < ZingerConfiguration.DegreeOfParallelism; i++)
                    {
                        searchWorkers[i] = Task.Factory.StartNew(SearchStateSpace, i);
                        System.Threading.Thread.Sleep(10);
                    }

                    // Wait for all readers to Finish
                    GLobalFrontierSet.WaitForAllReaders(CancelTokenZingExplorer.Token);
                    // Wait for all search workers to Finish
                    Task.WaitAll(searchWorkers);
                    // Wait for all writer to Finish
                    GLobalFrontierSet.WaitForAllWriters(CancelTokenZingExplorer.Token);
                    //For Debug
                    //GLobalFrontierSet.PrintAll();
                }
                catch (AggregateException ex)
                {
                    foreach (var inner in ex.InnerExceptions)
                    {
                        if ((inner is ZingException))
                        {
                            return lastErrorFound;
                        }
                        else
                        {
                            ZingerUtilities.PrintErrorMessage("Unknown Exception in Zing:");
                            ZingerUtilities.PrintErrorMessage(inner.ToString());
                            return ZingerResult.ZingRuntimeError;
                        }
                    }
                }

                ZingerStats.NumOfFrontiers = GLobalFrontierSet.Count();
                ZingerStats.PrintPeriodicStats();
            }
            while (GLobalFrontierSet.Count() > 0 && !ZingerConfiguration.zBoundedSearch.checkIfFinalCutOffReached());

            /*
            if (lastErrorFound != ZingerResult.Success)
                return ZingerResult.Assertion;
            else
                return ZingerResult.Success;
            */
            return lastErrorFound;
        }
Example #8
0
        public TaskRunSyncTaskScheduler(bool ableToExecuteInline)
        {
            AbleToExecuteInline = ableToExecuteInline;

            /*need at least two threads since we might schedule two tasks (parent-child)*/
            const int minThreads = 2;
            int numberOfThreads = Environment.ProcessorCount > minThreads ? Environment.ProcessorCount : minThreads;
            _threads = new Task[numberOfThreads];
            for (int i = 0; i < numberOfThreads; i++)
            {
                Task t = new Task(() =>
                {
                    foreach (var task in _tasks.GetConsumingEnumerable())
                    {
                        if (task.Status == TaskStatus.WaitingToRun)
                        {
                            ExecuteTask(task);
                        }
                    }
                });

                t.Start();
                _threads[i] = t;
            }
        }
 public TaskGroupAdapter(IEnumerable<Task> tasks)
 {
     this.tasks = tasks.ToArray();
     this.moduleTypes = tasks.SelectMany(t => t.Modules.Any() ? t.Modules.Select(m => m.GetType()) : new Type[] { null })
                             .Distinct()
                             .OrderBy(t => t?.Name ?? "ZZZ")
                             .ToArray();
 }
 public ParallelPersistor(ISession session, int asyncWorkersCount)
 {
     _session = session;
     _workerTasks = new Task[asyncWorkersCount];
     _maximumQueueSize = asyncWorkersCount * 100;
     _queriesWaitingInLineSemaphore = new SemaphoreSlim(_maximumQueueSize);
     _insertionQueue = new BufferBlock<PendingInsert>();
 }
        public void setTable(string data)
        {
            //convert string input data in cells

            string[] rows = data.Split(NEW_ROW);
            string[] row = rows[0].Split(TABULATION);

            table = new Table(row.Length, rows.Length);

            tasks = new Task[table.ColCount*table.RowCount];

            for (int i = 0; i < table.RowCount; i++)
            {
                rows[i] = rows[i].TrimEnd('\r');
                row = rows[i].Split(TABULATION);

                for (int j = 0; j < table.ColCount; j++)
                {
                    //copies for threads
                    int colIndex = j;
                    int rowIndex = i;
                    var cellData = row[colIndex];

                    tasks[table.ColCount * rowIndex + colIndex] = Task.Factory.StartNew(() =>
                        {
                            ICellCreater cellCreater = new CellCreater();
                            //buffer cell to avoid direct reference on table
                            Cell buf;
                            try
                            {
                                buf = cellCreater.GetCell(cellData);
                                if (buf is ExpressionCell)
                                {
                                    buf = Calculate(buf as ExpressionCell);
                                }
                                buf.IsChecked = true;
                                lock (table)
                                {
                                    table[colIndex, rowIndex] = buf;
                                }
                            }
                            catch (Exception ex)
                            {
                                buf = new ErrorCell(ex.Message);
                                buf.IsChecked = true;
                                lock (table)
                                {
                                    table[colIndex, rowIndex] = buf;
                                }
                            }
                        });

                }
            }
            Task.WaitAll(tasks);
            isSet = true;
        }
        protected ProducerConsumerQueueBase(int numberOfConsumers)
        {
            this.queue = new BlockingCollection<WorkItem>(numberOfConsumers);

            this.consumerTasks =
                Enumerable.Range(1, numberOfConsumers)
                    .Select(_ => Task.Factory.StartNew(this.Consume))
                    .ToArray();
        }
Example #13
0
	public void Initialize()
	{
		apply = new ApplyComponent();
		
		counter = 0;
		result = "";
		invoked = false;
		arr = new Task[4];
	}
        public ProducerConsumerQueue(int workerCount, TaskCreationOptions taskCreationOptions = TaskCreationOptions.None)
        {
            workerCount = Math.Max(1, workerCount);

            m_Workers = new Task[workerCount];
            for (int i = 0; i < workerCount; i++)
            {
                m_Workers[i] = Task.Factory.StartNew(Consume, taskCreationOptions);
            }
        }
Example #15
0
 /// <summary/>
 /// <param name="schedulableTasks">Tasks that will be scheduled and rescheduled</param>
 /// <param name="granularityInMilliseconds"></param>
 public Scheduler(
     Task[] schedulableTasks,
     int granularityInMilliseconds = 1000)
 {
     _schedulableTasks = schedulableTasks;
     _granularityInMilliseconds = granularityInMilliseconds;
     for (int i = _schedulableTasks.Length - 1; i >= 0; i--)
     {
         _taskQueue.Enqueue(_schedulableTasks[i]);
     }
 }
        public void Stop()
        {
            Trace.TraceInformation(string.Format(CultureInfo.InvariantCulture, "Device {0} status = Shutting down", DeviceId));
            _source.Cancel();

            Task.WaitAll(_runningTasks);
            Trace.TraceInformation(string.Format(CultureInfo.InvariantCulture, "Device {0} status = Down", DeviceId));

            _runningTasks = null;
            _connectors.Clear();
        }
Example #17
0
        public void Load()
        {
            _results = new ScheduleResults();

            var data = Task<ScheduleResults>.Factory.StartNew(() => new PackageScheduler(_sessionSize, _talkSize).OrganizeSchedule(_results, _cancelToken), _cancelToken);

            var brute = new Task<ScheduleResults>(()=> new Solver(_sessionSize,_talkSize).Pack(_results,_cancelToken), TaskCreationOptions.LongRunning);

            brute.Start();

            _tasks = new Task[] { data, brute };
        }
Example #18
0
        public Job(string name, Task[] tasks, Action callbackFinished, Action callbackStopped, Action callbackFailed)
        {
            state = JobStates.Created;

            // set parameter
            this.name = name;
            this.tasks = tasks;

            OnFailed = callbackFinished;
            OnFinished = callbackStopped;
            OnStopped = callbackFailed;
        }
Example #19
0
        public Job(string name, Task[] tasks)
        {
            state = JobStates.Created;

            // set parameter
            this.name = name;
            this.tasks = tasks;

            OnFailed = null;
            OnFinished = null;
            OnStopped = null;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TaskDispatcher" /> class.
        /// </summary>
        /// <param name="maxThreads">
        /// The number of background threads that will be made available for executing code.
        /// If 0 then will  default to the number of processors as reported by <c>Environment.ProcessorCount</c>.
        /// </param>
        public TaskDispatcher(int maxThreads = 0)
        {
            if (maxThreads == 0)
            {
                maxThreads = Environment.ProcessorCount;
            }

            this.lockObject = new object();
            this.taskArray = new Task[maxThreads];

            //// Debug.WriteLine("TaskDispatcher. Initialization with {0} tasks.", maxThreads);
        }
        public FixtureManager(int concurrencyLevel, IStreamListenerManager streamManager, Func<string, List<IResourceFacade>> getResourcesForSport)
        {
            GetResourcesForSportFunc = getResourcesForSport;
            _streamManager = streamManager;
            _streamManager.ProcessResourceHook = ReProcessFixture;

            _creationTasks = new Task[concurrencyLevel];
            for (var i = 0; i < concurrencyLevel; i++)
            {
                _creationTasks[i] = Task.Factory.StartNew(CreateFixture, _creationQueueCancellationToken.Token);
            }
        }
Example #22
0
 public DataProcessor()
 {
     var len = Math.Max(CurrencyStoreSection.Instance.Task.Capacity, 5);
     _tasks = new Task[len];
     for (int i = 0; i < len; i++)
     {
         var v = i;
         _tasks[i] = new Task(() => Process(v));
     }
     logger = new ElibLogging("trace");
     _service = ServiceFactory.GetService<ICurrencyService>();
 }
Example #23
0
        public void Start(int numOfTasks)
        {
            this.Tasks = new Task[numOfTasks];
            for (int idx = 0; idx < numOfTasks; idx++)
            {
                var task = new Task(() => { Execute(); });
                task.Start();
                this.Tasks[idx] = task;
            }

            Task.WaitAll(Tasks);
        }
		private void DdosCurrentQueue()
		{
			_consumerTasks = Enumerable.Range( 0, _consumerThreadCount )
				.Select( _ => Task.Run( () => RunConsumerAsync() ) )
				.ToArray();

			_producerTasks = Enumerable.Range( 0, _producerThreadCount )
				.Select( _ => Task.Run( () => RunProducer() ) )
				.ToArray();

			Task.WaitAll( _producerTasks );
			Task.WaitAll( _consumerTasks );
		}
Example #25
0
        private int _sizeData; // current nr of data items in queue

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="queueChangeEvent">Event that is set when something was added to the queue.</param>
        public TaskQueue(int queueSizeCmd, int queueSizeData, AutoResetEvent queueChangeEvent)
        {
            _maxSize = queueSizeCmd + queueSizeData;
            _maxSizeCmd = queueSizeCmd;
            _maxSizeData = queueSizeData;
            _queueChangeEvent = queueChangeEvent;
            _lock = new object();
            _tasks = new Task[_maxSize];
            _head = 0;
            _tail = 0;
            _sizeCmd = 0;
            _sizeData = 0;
        }
Example #26
0
        public void GivenAVariedSetOfTasksLoadedIntoTheTaskboard()
        {
            Given("that I have created a new database");
            var repos = _context.Get<IRepository<Task>>();

            var tasks = Enumerable.Range(0, 100).Select(_ => CreateRandomTask()).ToArray();

            repos.SaveAll(tasks);

            _loadedTasks = tasks;

            _context.Publish(new DatabaseChanged("whatever"));
        }
Example #27
0
 public ExportData(Events evnt, EventDay[] days, Task[] tasks, FacilityBookingConfirmed[][] facilities, Program[][] programs, Guest[][] guests, Participant[] participants
     , OptimizedBudgetItems optitems, BudgetIncome[] budgetincomes, Field[] field)
 {
     this.evnts = evnt;
     this.days = days;
     this.tasks = tasks;
     this.facilities = facilities;
     this.programs = programs;
     this.guests = guests;
     this.participants = participants;
     this.optitems = optitems;
     this.budgetincomes = budgetincomes;
     this.field = field;
 }
Example #28
0
        public HttpLoader(HttpLoaderSettings settings)
        {
            this.concurrent = settings.ConcurrentConnections;
            this.reqCount = settings.TotalRequests;
            this.requests = new Task[this.concurrent];

            this.url = settings.URL;

            this.notify = new ManualResetEvent(false);
            this.Complete = new ManualResetEvent(false);

            this.Tag = settings.Tag;
            this.Status = Status.Enqueued;
        }
Example #29
0
    private void GenerateRoutine(TextAsset tA)
    {
        string[] entries = tA.text.Split('\n');
        string[] splits;
        tasks = new Task[entries.Length];
        timetable = new float[entries.Length];

        for(int i = 0; i < entries.Length; i++)
        {
            splits = entries[i].Split(',');
            timetable[i] = float.Parse(splits[0].Trim()) * 60.0f;             //Gets the execution time in minutes.
            tasks[i] = (Task)Enum.Parse(typeof(Task), splits[1].Trim());     //Gets the task to start executing at that time.
        }
    }
Example #30
0
 public BuildResult(
     Task[] tasks,
     AssemblyReference[] references,
     EnvironmentVariable[] variables,
     byte[] assembly,
     byte[] symbols)
 {
     Tasks = tasks;
     References = references;
     AssemblyBytes = assembly;
     SymbolBytes = symbols;
     Variables = variables;
     Assembly = Load();
     Reflect();
 }