Esempio n. 1
0
        static void Main()
        {
            Mathmatics   math = new Mathmatics();
            WorkDelegate work = math.Calculate;

            work('+', 10, 5);
        }
 private void ThreadFunc()
 {
     lock ( workLock ) {
         int shouldStop = 0;
         do
         {
             shouldStop = Interlocked.Exchange(ref stop,
                                               stop);
             if (shouldStop == 0)
             {
                 WorkDelegate workItem = null;
                 if (Monitor.Wait(workLock, WAIT_TIMEOUT))
                 {
                     // Process the item on the front of the
                     // queue
                     lock ( workQueue ) {
                         workItem =
                             (WorkDelegate)workQueue.Dequeue();
                     }
                     workItem();
                 }
             }
         } while(shouldStop == 0);
     }
 }
Esempio n. 3
0
        /// <summary>
        /// The consumer call that will call the work event and pass in the
        /// work item.
        /// </summary>
        /// <param name="obj">The work item</param>
        protected void Consume(Object obj)
        {
            WorkItem item = obj as WorkItem;

            if (item != null)
            {
                WorkDelegate localEvent = workEvent;
                if (localEvent != null)
                {
                    // Call the work event
                    localEvent(item.Item);
                    lock (this)
                    {
                        workLength--;
                        if (!workComplete)
                        {
                            return;
                        }
                    }
                    if (workLength == 0)
                    {
                        // Reset the manual reset object when all work is complete
                        if (resetEvent != null)
                        {
                            resetEvent.Set();
                        }
                        // At least one work event has been completed
                        enqueuOnce = true;
                    }
                }
            }
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            Mathematics  math = new Mathematics();
            WorkDelegate work = math.Calculate;     // 수학관련 클래스의 메소드를 델리게이트에 저장한다.

            // 함수포인터처럼 사용할 수 있다.
            work(10, '+', 5);
            work(10, '-', 5);
            work(10, '*', 5);
            work(10, '/', 5);

            Console.WriteLine();

            // 델리게이트에 각 메소드들을 연산 및 저장으로 인스턴스를 추가한다.
            // CalcDelegate calc;       // 그냥 선언만 해도 되지만 이후 += 연산이 불가능하다.
            CalcDelegate calc = Add;    // 메소드 대입연산이 존재해야 이후 += 인스턴스 추가  가능하다.

            calc += Sub;
            calc += Mul;
            calc += Div;

            calc(4, 2);     // 델리게이트에 저장된 인스턴스들을 모두 실행한다.

            Console.WriteLine();

            calc -= Sub;    // 인스턴스를 뺄 수 있다.

            calc(4, 2);     // 남아있는 인스턴스들로만 연산을 한다.
        }
Esempio n. 5
0
 public ThreadTask(WorkDelegate work, string id, string displayName, Object transactionParamsObj)
 {
     Id                   = id;
     DisplayName          = displayName;
     Work                 = work;
     TransactionParamsObj = transactionParamsObj;
 }
Esempio n. 6
0
            public void AddWork(WorkDelegate work)
            {
                AutoResetEvent myEvent = new AutoResetEvent(false);

                eventQueue.Enqueue(myEvent);
                eventQueue.TryPeek(out AutoResetEvent head);
                while (head != myEvent)
                {
                    head.Dispose();
                    myEvent.WaitOne();
                    eventQueue.TryPeek(out head);
                }
                head.Dispose();
                work();

                //lock to prevent race condition
                lock (this)
                {
                    //Remove my event from queue
                    eventQueue.TryDequeue(out head);
                    head.Dispose();
                    //signal next thread
                    eventQueue.TryPeek(out head);
                    head.Set();
                    head.Dispose();
                }
            }
Esempio n. 7
0
 public void SubmitWorkItem(WorkDelegate item)
 {
     lock (_workQueue)
     {
         _workQueue.Enqueue(item);
     }
     _semaphore.Release();
 }
    public void SubmitWorkItem(WorkDelegate item)
    {
        lock ( workLock ) {
            lock ( workQueue ) {
                workQueue.Enqueue(item);
            }

            Monitor.Pulse(workLock);
        }
    }
Esempio n. 9
0
        static void Main(string[] args)
        {
            Mathematics  math = new Mathematics();
            WorkDelegate work = math.Calculate;

            work('+', 10, 5);
            work('-', 10, 5);
            work('*', 10, 5);
            work('/', 10, 5);
        }
Esempio n. 10
0
 public void SubmitWorkItem(WorkDelegate item)
 {
     lock (_workLock)
     {
         lock (_workQueue.SyncRoot)
         {
             _workQueue.Enqueue(item);
         }
         Monitor.Pulse(_workLock);
     }
 }
Esempio n. 11
0
    static void Main(string[] args)
    {
        Mathematics  math = new Mathematics();
        WorkDelegate work = math.Calculate;  // WorkDelegate를 호출하면 Calculate를 호출한다.

        work('+', 10, 6);
        work('-', 10, 6);
        work('*', 10, 6);
        work('/', 10, 6);
        work('%', 10, 6);
    }
Esempio n. 12
0
 /// <summary>
 /// 初始化
 /// </summary>
 public QueueManager()
 {
     if (_msgsQueue == null)
     {
         if (!Directory.Exists(Path))
         {
             Directory.CreateDirectory(Path);
         }
         _msgsQueue = new Queue <Msg>();
         _workDg    = new WorkDelegate(Work);
     }
 }
Esempio n. 13
0
        /// <summary>
        /// Build a final work delegate
        /// </summary>
        /// <returns></returns>
        public WorkDelegate <TWorkContext> Build()
        {
            // add a WorkDelegate that do nothing to prevent null object error happens
            WorkDelegate <TWorkContext> last = context => Task.CompletedTask;
            // the combined WorkDelegate
            WorkDelegate <TWorkContext> work = last;

            this._middlewares.Reverse();
            foreach (var mw in this._middlewares)
            {
                work = mw(work);
            }
            return(work);
        }
Esempio n. 14
0
        static void Main(string[] args)
        {
            //CarDelegate dealer;
            //dealer = Car;
            //dealer();
            //Car();
            Mathematics  math = new Mathematics();
            WorkDelegate work = math.Calculate;

            work('+', 10, 5);
            work('-', 10, 5);
            work('*', 10, 5);
            work('/', 10, 5);
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            Mathematics math = new Mathematics();
            // 대리자에 해당 메서드를 직접 전달한다.
            WorkDelegate work = math.Calculate;

            char OpCode = new char();

            Console.WriteLine("연산을 위해서 다음 부호를 입력해주세요. [\"+,-,*,/\"]");
            //정상적인 부호가 입력될때까지 Loop
            while (false == IsOpCode(Console.ReadKey(), ref OpCode))
            {
                Console.WriteLine();
                Console.WriteLine("부호를 다시 입력해주세요. [\"+,-,*,/\"]. 당신이 입력한 값 {0}", OpCode);
            }
            Console.WriteLine();

            int arg2;

            Console.WriteLine("연산을 위한 첫번째 수를 입력해주세요.");
            while (false == int.TryParse(Console.ReadLine(), out arg2))
            {
                Console.WriteLine("연산을 위한 첫번째 수를 다시 입력해주세요. 당신이 입력한 값 {0}", arg2);
            }

            int arg3;

            Console.WriteLine("연산을 위한 두번째 수를 입력해주세요.");
            while (false == int.TryParse(Console.ReadLine(), out arg3))
            {
                Console.WriteLine("연산을 위한 두번째 수를 다시 입력해주세요. 당신이 입력한 값 {0}", arg3);
            }

            work(OpCode, arg2, arg3);

            Console.WriteLine("아무 입력이나 누르면 프로그램을 종료됩니다.");
            Console.ReadKey();
        }
        //#method
        public int Join(WorkDelegate workDelegate, Object paramObj)
        {
            lock (_threadLock)
            {
                _id++;
                var task = new Task(_id, paramObj, workDelegate);
                task.JoinTime = SystemTimeHelper.Now();
                task.Status   = TaskStatus.Waiting;
                _tasks.Add(task);

                if (OnTaskJoin != null)
                {
                    var args = new TaskIdParamObjEventArgs(_id, paramObj);
                    OnTaskJoin(this, args);
                }

                var processingTasks = _tasks.Where(x => x.Status == TaskStatus.Processing);
                var processingTaskIdentityFlagList = processingTasks.Where(x => !x.IdentityFlag.IsNullOrEmpty()).Select(x => x.IdentityFlag).Distinct().ToList();
                if (!task.IdentityFlag.IsNullOrEmpty() & processingTaskIdentityFlagList.Contains(task.IdentityFlag))
                {
                    return(_id);
                }

                int i;
                for (i = 0; i < _workerCount; i++)
                {
                    if (!_workers[i].IsBusy)
                    {
                        task.WorkerId = i;
                        task.Status   = TaskStatus.Processing;
                        RaiseDoWork(_workers[i], task);
                        break;
                    }
                }
                return(_id);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Used to add work to the queue.
        /// </summary>
        /// <param name="WorkObject">The work object.</param>
        /// <param name="Delegate">The delegate.</param>
        public void QueueWork(object WorkObject, WorkDelegate Delegate)
        {
            WorkItem wi = new WorkItem();

            wi.WorkObject = WorkObject;
            wi.Delegate   = Delegate;
            lock (WorkQueue)
            {
                WorkQueue.Enqueue(wi);
            }

            //Now see if there are any threads that are idle
            bool FoundIdleThread = false;

            foreach (WorkThread wt in ThreadList)
            {
                if (!wt.Busy)
                {
                    wt.WakeUp();
                    FoundIdleThread = true;
                    break;
                }
            }

            if (!FoundIdleThread)
            {
                //See if we can create a new thread to handle the additional workload
                if (ThreadList.Count < m_MaxThreads)
                {
                    WorkThread wt = new WorkThread(ref WorkQueue);
                    lock (ThreadList)
                    {
                        ThreadList.Add(wt);
                    }
                }
            }
        }
Esempio n. 18
0
        public string Join(WorkDelegate workDelegate, string displayName, Object transactionParams)
        {
            lock (_threadLock)
            {
                var id   = "".ToUniqueStringByShortGuid(null);
                var task = new ThreadTask(workDelegate, id, displayName, transactionParams);
                task.JoinTime = SystemTimeHelper.Now();
                task.Status   = TaskStatus.Waiting;
                _tasks.Add(task);

                if (OnTaskJoin != null)
                {
                    var args = new TaskEventArgs(id, displayName, transactionParams);
                    OnTaskJoin(this, args);
                }

                int  i;
                bool isWorkerPoolBusy = true;
                for (i = 0; i < _workerNum; i++)
                {
                    if (!_workers[i].IsBusy)
                    {
                        task.WorkerId = i;
                        task.Status   = TaskStatus.Processing;
                        RaiseWork(_workers[i], task);
                        isWorkerPoolBusy = false;
                        break;
                    }
                }
                if (isWorkerPoolBusy)
                {
                    task.Status = TaskStatus.Waiting;
                }
                return(id);
            }
        }
Esempio n. 19
0
        public void Work()
        {
            // don't allow to start a second time
            if (m_progress.IsStarted)
                return;

            WorkDelegate d = new WorkDelegate(DoWork);
            m_startTime = DateTime.Now;
            m_progress.Start();
            d.BeginInvoke(new AsyncCallback(CallbackMethod), d);
        }
Esempio n. 20
0
 public Work(object param, WorkDelegate fun)
 {
     this.param = param;
     this.fun   = fun;
 }
 public Task(int id, Object param, WorkDelegate work)
 {
     Work     = work;
     ParamObj = param;
     Id       = id;
 }
Esempio n. 22
0
 public static void SendWXMessage_AddNewProduct(ProductInfo product)
 {
     bool flag;
     AsyncWorkDelegate delegate2 = new AsyncWorkDelegate();
     IAsyncResult      result    = new WorkDelegate(delegate2.CalData).BeginInvoke(product, out flag, null, null);
 }
Esempio n. 23
0
 public TaskWorker(WorkDelegate run, string id = null) : this(id)
 {
     _workDelegate = run;
 }
Esempio n. 24
0
 public TaskWorker(WorkDelegate run, string id = null)
     : this(id)
 {
     _workDelegate = run;
 }
Esempio n. 25
0
 public TaskWorker(WorkDelegate run)
 {
     _workDelegate = run;
 }