Example #1
0
 //异步页面的任务启动方法
 public IAsyncResult OnBegin(object sender, EventArgs e,
     AsyncCallback cb, object extraData)
 {
     _proc = new WaitCallback(ChatInvokeProc);
     Hashtable theUser = new Hashtable();
     theUser = (Hashtable)extraData;
     string user = theUser["guid"].ToString();
     _guid = user;
     Thread.CurrentThread.Name = "上下文线程" + user;
     //用户处理,不存在则增加,即为登录
     theUser["asyn"] = this;
     theUser["lastUpdateTime"] = DateTime.Now.ToString();
     Hashtable feachUser = new Hashtable();
     bool isInCach=false;
     for (var i = 0; i < globalCache.userCache.Count; i++)
     {
         feachUser = (Hashtable)globalCache.userCache[i];
         if (theUser["guid"].ToString() == feachUser["guid"].ToString())
         {
             globalCache.userCache[i] = theUser;
             isInCach = true;
         }
     }
     if (!isInCach)
     {
         globalCache.userCache.Add(theUser);
     }
     //开始异步执行,这里会开启一个新的辅助线程
     return _proc.BeginInvoke(extraData, cb, extraData);
 }
Example #2
0
		public WorkItem(WorkItemId taskID, WaitCallback wc, IAsyncResult state, ExecutionContext ctx)
		{
			_callback = wc;
			_state = state;
			_ctx = ctx;
			_taskID = taskID;
		}
 public virtual IMessageCtrl AsyncProcessMessage(IMessage reqMsg, IMessageSink replySink)
 {
     ADAsyncWorkItem item = new ADAsyncWorkItem(reqMsg, this, replySink);
     WaitCallback callBack = new WaitCallback(item.FinishAsyncWork);
     ThreadPool.QueueUserWorkItem(callBack);
     return null;
 }
 public override object BeginExecute(WaitCallback waitCallback, object state)
 {
     Thread result = new Thread(new ParameterizedThreadStart(waitCallback));
     result.IsBackground = true;
     result.Start(state);
     return result;
 }
Example #5
0
 // this function adds an item to the queue, and takes care of updating the counters.
 // All functions added to the queue should be wrapped in this wrapper.
 public void QueueItemWrapper(WaitCallback workFunction, object parametersIn)
 {
     lock (counterLock)
     {
         queueLength--;
         analysisThreadCount++;
     }
     try
     {
         workFunction(parametersIn);
     }
     catch (Exception e)
     {
         // if there's an exception thrown while adding a block then we're
         // pretty much stuck. The best we can do is log it and eat it to
         // stop it killing the rest of the program.
         controller.log("Exception thrown analysing " + parametersIn.ToString());
         controller.errorLog("Exception thrown analysing " + parametersIn.ToString());
         controller.errorLog(e.ToString());
         controller.errorLog("======================");
         controller.errorLog("");
         return;
     }
     finally
     {
         lock (counterLock) analysisThreadCount--;
     }
     lock (counterLock)
     {
         totalAnalysed++;
         currentAnalysisTotal++;
     }
 }
		protected internal override void Schedule (WaitCallback callback, Guid workflowInstanceId, DateTime whenUtc, Guid timerId)
		{
			//WorkflowInstance wi = WorkflowRuntime.GetInstanceFromGuid (workflowInstanceId);

			//wi.TimerEventSubscriptionCollection.Add
			//	(new TimerEventSubscription (workflowInstanceId, timerId));
		}
 public static void Enqueue(WaitCallback callback, Policy policy)
 {
     switch(policy)
     {
         case Policy.Immediate:
             logger.Info("Immediately running callback {0}",
                 callback.Method.Name);
             ThreadPool.QueueUserWorkItem(new WaitCallback(callback));
             break;
         case Policy.Queued:
             lock (queue)
             {
                 if (cooledDown)
                 {
                     logger.Info("Immediately putting callback {0}",
                         callback.Method.Name);
                     ThreadPool.QueueUserWorkItem(
                         new WaitCallback(callback));
                 }
                 else
                 {
                     logger.Debug("Queuing callback {0} for later execution",
                         callback.Method.Name);
                     queue.Add(callback);
                 }
             }
             break;
     }
 }
 /// <summary>
 /// constructor
 /// </summary>
 public ThreadServerReceive(WaitCallback callback, dpslamServer server, ArrayList receive_buffer)
 {
     if (callback == null) throw new ArgumentNullException("callback");
     _callback = callback;
     _server = server;
     _buffer = receive_buffer;
 }
 public CallbackInfo(WaitCallback callback, Guid instanceId, Guid timerId, DateTime when)
 {
     this.callback = callback;
     this.when = when;
     this.instanceId = instanceId;
     this.timerId = timerId;
 }
Example #10
0
 /// <summary>构造一个线程任务</summary>
 /// <param name="method">任务方法</param>
 /// <param name="abortMethod">任务被取消时执行的方法</param>
 /// <param name="argument">任务参数</param>
 public ThreadTask(WaitCallback method, WaitCallback abortMethod, Object argument)
 {
     Method = method;
     Argument = argument;
     ID = newID;
     AbortMethod = abortMethod;
 }
Example #11
0
        public void QueueUserWorkItem(WaitCallback worker, object arg)
        {
            if(worker == null)
            {
                throw new ArgumentNullException("Invalid WaitCallback passed");
            }

            if(!this.closed)
            {
                lock(syncRoot)
                {
                    if(!this.closed || !this.closing)
                    {
                        this.workQueue.Enqueue(new Future(worker, arg));

                        if(!this.running)
                        {
                            this.executionComplete.Reset();
                            this.running = true;
                            ThreadPool.QueueUserWorkItem(new WaitCallback(QueueProcessor), null);
                        }
                    }
                }
            }
        }
 internal PageAsyncTaskManager(Page page)
 {
     this._page = page;
     this._app = page.Context.ApplicationInstance;
     this._tasks = new ArrayList();
     this._resumeTasksCallback = new WaitCallback(this.ResumeTasksThreadpoolThread);
 }
        public void ThreadSafeQueueTest()
        {
            var q = new ThreadSafeQueue<string>();

            var methodFill = new WaitCallback(s =>
            {
                for (var i = 0; i < 33; i++)
                {
                    Assert.IsTrue(q.InQueue("iter" + i, 1000));
                    Thread.Sleep(20);
                }
            });
            var methodFlush = new WaitCallback(s =>
                {
                    var countRead = 0;
                    for (var i = 0; i < 40; i++)
                    {
                        bool timeout;
                        var items = q.ExtractAll(1000, out timeout);
                        countRead += items.Count;
                        Thread.Sleep(20);
                    }
                    Assert.IsTrue(countRead > 0);
                });
            ThreadPool.QueueUserWorkItem(methodFill);
            ThreadPool.QueueUserWorkItem(methodFlush);
        }
 /// <summary>
 /// constructor
 /// </summary>
 public WebcamVisionThreadGrabFrameMulti(WaitCallback callback, object data, bool loop)
 {
     if (callback == null) throw new ArgumentNullException("callback");
     _callback = callback;
     _data = data;
     _loop = loop;
 }
Example #15
0
		/// <summary>
		/// Timer initialization
		/// </summary>
		/// <param name="workFunction">Job working function</param>
		/// <param name="timerDueTime">Timer start delay</param>
		/// <param name="timerPeriod">Timer working interval</param>
		public ServiceJob(WaitCallback workFunction, int timerDueTime, int timerPeriod)
		{
			Execute = workFunction;

			TimerDueTime = timerDueTime;
			TimerPeriod = timerPeriod;
		}
Example #16
0
		/// <summary>
		/// Timer initialization
		/// </summary>
		/// <param name="workFunction">Job working function</param>
		/// <param name="workingPoints">Working time points</param>
		public ServiceJob(WaitCallback workFunction, IList<DateTime> workingPoints)
		{
			if (workingPoints == null) throw new ArgumentNullException("workingPoints");

			Execute = workFunction;
			WorkingPoints = workingPoints;
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="AxAsyncProgress"/> class.
        /// </summary>
        public AsyncDialogForm(string formCaption, IExecutorService executorService,
            int minimum, int maximum,
            AsyncWaitCallback callback,
            AsyncWaitCallback finishedCallback,
            AsyncWaitCallback abortCallback)
        {
            InitializeComponent();
            SetTagProperty();
            this.ResolveResources();
            _elapsedTimer = AsyncProgressTimerFactory.Create();
            _executorService = executorService;
            _actualCallback = new WaitCallback(this.ExecAsync);
            _updateStatus = new UpdateAsyncStatusHandler(this.UpdateStatus);
            _updateStatusProgress = new UpdateAsyncStatusProgressHandler(this.UpdateStatusProgress);
            _enableButton = new EnableButtonHandler(this.EnableOKButton);
            this.InitializeProgress(minimum, maximum);

            btnCancel.Enabled = (_executorService != null);
            if (_executorService != null)
            {
                IExecutorService2 executor2 = _executorService as IExecutorService2;
                if (executor2 != null)
                {
                    executor2.Reset();
                }
            }

            this.Text = formCaption;
            lblStatus.Text = formCaption;
            this.Initialize(callback, finishedCallback, abortCallback, this);
        }
Example #18
0
        // Main executing of commands
        internal string Execute(string clientId, string sessionId, string commands, string callback)
        {
            Log(clientId, sessionId, commands);

            string newSessionId = TTE.NewSessionId();

            try {
                string cleanCommands = _statementProcessor.Clean(commands);
                string[] splitCommands = _statementProcessor.Split(cleanCommands, false);
                ArrayList instantiatedCommands = _statementProcessor.Instantiate(splitCommands, clientId, newSessionId, callback);

                foreach (CommandContainer command in instantiatedCommands) {
                    command.OrigSessionId = sessionId;
                    _commandProcessor.Create(command);
                }

                // The callback value should be a http, https or tcp connection string, this will be called when the process has stopped running
                if (callback != "") {
                    WaitCallback wc = new WaitCallback(ProcessCommand);
                    ThreadPool.QueueUserWorkItem(wc, newSessionId);
                } else {
                    ProcessCommand(newSessionId);
                }
            } catch (Exception ex) {
                Log(ex); _messageProcessor.Create(clientId, newSessionId, Config.ClientId, enmMessageCategory.Exception, ex.Message);
            }

            return newSessionId;
        }
Example #19
0
 /// <summary>
 /// Enqueues action.
 /// </summary>
 /// <param name="callback"></param>
 public void Queue(WaitCallback callback)
 {
     if (!ThreadPool.QueueUserWorkItem(callback))
     {
         throw new QueueFullException("Unable to add item to pool: " + callback.Target);
     }
 }
Example #20
0
 // ctor
 internal RequestQueue(int minExternFreeThreads, int minLocalFreeThreads, int queueLimit) {
     _minExternFreeThreads = minExternFreeThreads;
     _minLocalFreeThreads = minLocalFreeThreads;
     _queueLimit = queueLimit;
     
     _workItemCallback = new WaitCallback(this.WorkItemCallback);
 }
 internal QuotaThrottle(WaitCallback release, object mutex)
 {
     this.limit = Int32.MaxValue;
     this.mutex = mutex;
     this.release = release;
     this.waiters = new Queue<object>();
 }
Example #22
0
        public void Open()
        {
            if (listenSockets == null)
            {
                listenSockets = new List<Socket>();
                if (!ipAddress.Equals(IPAddress.Broadcast))
                {
                    listenSockets.Add(CreateListenSocket(this.ipAddress, this.port, multicast));
                }
                else
                {
                    listenSockets.Add(CreateListenSocket(IPAddress.Any, this.port, multicast));
                    if (Socket.OSSupportsIPv6)
                    {
                        listenSockets.Add(CreateListenSocket(IPAddress.IPv6Any, this.port, multicast));
                    }
                }
            }

            this.onReceive = new AsyncCallback(this.OnReceive);
            WaitCallback startReceivingCallback = new WaitCallback(StartReceiving);

            Socket[] socketsSnapshot = listenSockets.ToArray();
            for (int i = 0; i < socketsSnapshot.Length; i++)
            {
                ThreadPool.QueueUserWorkItem(startReceivingCallback, socketsSnapshot[i]);
            }
        }
Example #23
0
        public void Add(Action op)
        {
            if (!Running) return;

            var wc = new WaitCallback(_ => Executor.Execute(op));
            ThreadPool.UnsafeQueueUserWorkItem(wc, null);
        }
        /// <summary>
        /// This method takes as input the connection string to an SQL Server database
        /// and creates a corresponding SQLite database file with a schema derived from
        /// the SQL Server database.
        /// </summary>
        /// <param name="sqlServerConnString">The connection string to the SQL Server database.</param>
        /// <param name="sqlitePath">The path to the SQLite database file that needs to get created.</param>
        /// <param name="password">The password to use or NULL if no password should be used to encrypt the DB</param>
        /// <param name="handler">A handler delegate for progress notifications.</param>
        /// <param name="selectionHandler">The selection handler that allows the user to select which
        /// tables to convert</param>
        /// <remarks>The method continues asynchronously in the background and the caller returned
        /// immediatly.</remarks>
        public static void ConvertSqlServerToSQLiteDatabase(string sqlServerConnString,
            string sqlitePath, string password, SqlConversionHandler handler, 
            SqlTableSelectionHandler selectionHandler,
            FailedViewDefinitionHandler viewFailureHandler,
            bool createTriggers)
        {
            // Clear cancelled flag
            _cancelled = false;

            WaitCallback wc = new WaitCallback(delegate(object state)
            {
                try
                {
                    _isActive = true;
                    ConvertSqlServerDatabaseToSQLiteFile(sqlServerConnString, sqlitePath, password, handler, selectionHandler, viewFailureHandler, createTriggers);
                    _isActive = false;
                    handler(true, true, 100, "Finished converting database");
                }
                catch (Exception ex)
                {
                    _log.Error("Failed to convert SQL Server database to SQLite database", ex);
                    _isActive = false;
                    handler(true, false, 100, ex.Message);
                } // catch
            });
            ThreadPool.QueueUserWorkItem(wc);
        }
        protected internal override void Schedule(WaitCallback callback, Guid workflowInstanceId)
        {
            if (callback == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("callback");
            }

            WorkflowDispatchContext currentDispatchContext = WorkflowDispatchContext.Current;

            if (currentDispatchContext != null && currentDispatchContext.IsSynchronous)
            {
                callback(workflowInstanceId);
            }
            else
            {
                if (this.syncContext != null)
                {
                    SynchronizationContextPostHelper.Post(this.syncContext, Fx.ThunkCallback(new SendOrPostCallback(callback)), workflowInstanceId);
                }
                else
                {
                    base.Schedule(callback, workflowInstanceId);
                }
            }
        }
        /// <summary>
        /// Starts the Web Service
        /// </summary>
        /// <param name="listeningAtUrlBase">
        /// A Uri that acts as the base that the server is listening on.
        /// Format should be: http://127.0.0.1:8080/ or http://127.0.0.1:8080/somevirtual/
        /// Note: the trailing slash is required! For more info see the
        /// HttpListener.Prefixes property on MSDN.
        /// </param>
        protected void Start(string listeningAtUrlBase, WaitCallback listenCallback)
        {
            // *** Already running - just leave it in place
            if (this.IsStarted)
                return;

            if (this.Listener == null)
                Listener = new System.Net.HttpListener();

            HostContext.Config.HandlerFactoryPath = ListenerRequest.GetHandlerPathIfAny(listeningAtUrlBase);

            Listener.Prefixes.Add(listeningAtUrlBase);

            try
            {
                Listener.Start();
                IsStarted = true;
            }
            catch (HttpListenerException ex)
            {
                if (Config.AllowAclUrlReservation && ex.ErrorCode == 5 && registeredReservedUrl == null)
                {
                    registeredReservedUrl = AddUrlReservationToAcl(listeningAtUrlBase);
                    if (registeredReservedUrl != null)
                    {
                        Start(listeningAtUrlBase, listenCallback);
                        return;
                    }
                }

                throw ex;
            }

            ThreadPool.QueueUserWorkItem(listenCallback);
        }
Example #27
0
		protected override void Schedule (WaitCallback callback, Guid workflowInstanceId)
		{
			Console.WriteLine ("*** ourDefaultWorkflowSchedulerService::Schedule {0} {1}",
				callback, workflowInstanceId);

			base.Schedule (callback, workflowInstanceId);
		}
Example #28
0
        public void Listen(Action<TransportListener, TransportAsyncCallbackArgs> callback)
        {
            this.notifyAccept = this.NotifyAccept;
            this.acceptCallback = callback;

            this.OnListen();
        }
Example #29
0
	internal AsyncResult (WaitCallback cb, object state, bool capture_context)
	{
		async_state = state;
		async_delegate = cb;
		if (capture_context)
			current = ExecutionContext.Capture ();
	}
Example #30
0
      		protected override void Schedule(WaitCallback callback, Guid workflowInstanceId, DateTime whenUtc, Guid timerId)
      		{
      			Console.WriteLine ("*** ourDefaultWorkflowSchedulerService::Schedule {0} {1} {2}",
				callback, workflowInstanceId, whenUtc);

			base.Schedule (callback, workflowInstanceId, whenUtc, timerId);
      		}
Example #31
0
 protected internal abstract void Schedule(WaitCallback callback, Guid workflowInstanceId, DateTime whenUtc, Guid timerId);
Example #32
0
 protected internal abstract void Schedule(WaitCallback callback, Guid workflowInstanceId);
Example #33
0
        /// <summary>延迟执行一个委托</summary>
        /// <param name="callback"></param>
        /// <param name="ms"></param>
        /// <returns></returns>
        public static TimerX Delay(WaitCallback callback, Int32 ms)
        {
            var timer = new TimerX(callback, null, ms, 0);

            return(timer);
        }
Example #34
0
 protected abstract AsyncCompletionResult StartWritingStreamedMessage(Message message, TimeSpan timeout, WaitCallback callback, object state);
Example #35
0
 protected abstract AsyncCompletionResult BeginCloseOutput(TimeSpan timeout, WaitCallback callback, object state);
Example #36
0
 /// <summary>
 /// Queues a user work item to the thread pool.
 /// </summary>
 /// <param name="callback">
 /// A WaitCallback representing the delegate to invoke when the thread in the
 /// thread pool picks up the work item.
 /// </param>
 public static void QueueUserWorkItem(WaitCallback callback)
 {
     // Queue the delegate with no state
     QueueUserWorkItem(callback, null);
 }
Example #37
0
 public ThreadPoolItem(WaitCallback callback, object state)
 {
     Callback = callback;
     State    = state;
 }
Example #38
0
 public static bool QueueUserWorkItem(WaitCallback callBack, object state);
Example #39
0
        public void UpdatePlayList()
        {
            WaitCallback callBack = null;

            WaitCallback callback2 = null;

            lock (this.Playlist)
            {
                this.Playlist = PageSwitcher.Playlist;

                if (callBack == null)
                {
                    callBack = delegate(object state)
                    {
                        bool flag = false;

                        while (!flag)
                        {
                            Thread.Sleep(0x3e8);

                            flag = true;

                            foreach (MediaListModel model in PageSwitcher.Playlist)
                            {
                                if (!model.Downloaded)
                                {
                                    flag = false;
                                }
                            }
                        }

                        this.PlayNextVideo();
                    };
                }

                ThreadPool.QueueUserWorkItem(callBack);

                if (callback2 == null)
                {
                    callback2 = delegate(object r)
                    {
                        lock (this.FileLock)
                        {
                            XmlSerializer serializer = new XmlSerializer(typeof(List <MediaListModel>));

                            FileInfo info = new FileInfo(Constants.PlayListFile);

                            if (!File.Exists(Constants.PlayListFile))
                            {
                                StreamWriter writer = info.CreateText();

                                serializer.Serialize((TextWriter)writer, PageSwitcher.Playlist);

                                writer.Close();
                            }

                            else
                            {
                                info.Delete();

                                StreamWriter writer2 = info.CreateText();

                                serializer.Serialize((TextWriter)writer2, PageSwitcher.Playlist);

                                writer2.Close();
                            }
                        }
                    };
                }

                ThreadPool.QueueUserWorkItem(callback2);
            }
        }
Example #40
0
 public WaitCallBackWrapper(WaitCallback waitCallBack, object state)
 {
     this.WaitCallBack = waitCallBack;
     this.State        = state;
 }
Example #41
0
        /// <summary>
        /// 请求线程执行
        /// </summary>
        /// <param name="useradata">用户数据</param>
        /// <param name="callback">线程操作回调</param>
        public void Start(object useradata, WaitCallback callback)
        {
            var thread = this.GetThread();

            thread.Start(useradata, callback);
        }
Example #42
0
        public static void Main(string[] args)
        {
            var lockPayload = new WaitCallback(
                state =>
            {
                while (true)
                {
                    var syncMeth = new SyncWithLock();
                    var result   = syncMeth.GetData(5);
                    Console.WriteLine($"Accessing data {result} from thread {Thread.CurrentThread.ManagedThreadId}");
                    Thread.Sleep(100);
                }
            });

            var monitorPayload = new WaitCallback(
                state =>
            {
                while (true)
                {
                    var syncMeth = new SyncWithMonitor();
                    var result   = syncMeth.GetData(5);
                    Console.WriteLine($"Accessing data {result} from thread {Thread.CurrentThread.ManagedThreadId}");
                    Thread.Sleep(100);
                }
            });

            //ThreadPool.QueueUserWorkItem(monitorPayload);
            //ThreadPool.QueueUserWorkItem(monitorPayload);
            //ThreadPool.QueueUserWorkItem(monitorPayload);

            var autoResetPayload = new ThreadStart(
                () =>
            {
                string name = Thread.CurrentThread.ManagedThreadId.ToString();

                Console.WriteLine("{0} waits on AutoResetEvent #1.", name);
                event1.WaitOne();
                Console.WriteLine("{0} is released from AutoResetEvent #1.", name);

                Console.WriteLine("{0} waits on AutoResetEvent #2.", name);
                event2.WaitOne();
                Console.WriteLine("{0} is released from AutoResetEvent #2.", name);

                Console.WriteLine("{0} ends.", name);
            });

            var t1 = new Thread(autoResetPayload);
            var t2 = new Thread(autoResetPayload);

            //t1.Start();
            //t2.Start();
            //Thread.Sleep(35000);
            //event1.Set();
            //Thread.Sleep(35000);
            //event2.Set();

            var parallel = new ParallelExamples();
            //parallel.RunForInSync();
            //parallel.RunForInParallel();
            //parallel.RunForeachInParallel();
            //parallel.RunParallelInvoke();

            var readStream = new StreamExample();

            //readStream.ReadFromStreamApm();

            Task.Run(
                async() =>
            {
                await readStream.ReadFromStreamAsync();
            });

            Task.Run(
                () =>
            {
                while (true)
                {
                    Console.WriteLine("HELLO FROM OTHER TASK");
                    Thread.Sleep(500);
                }
            });

            Console.ReadLine();
        }
Example #43
0
 public WorkerContext(WaitCallback runnableCallback,
                      object runnableState)
 {
     RunnableCallback = runnableCallback;
     RunnableState    = runnableState;
 }
Example #44
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnThreadPool_Click(object sender, EventArgs e)
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();
            Console.WriteLine();
            Console.WriteLine("***********************btnThreadPool_Click Start 主线程id {0}**********************************", Thread.CurrentThread.ManagedThreadId);

            //for (int i = 0; i < 5; i++)
            //{
            //    string name = string.Format("btnThreadPool_Click_{0}", i);
            //    WaitCallback method = t => this.TestThread(t.ToString());
            //    ThreadPool.QueueUserWorkItem(method, name);
            //}
            ManualResetEvent mre    = new ManualResetEvent(false);
            WaitCallback     method = t =>
            {
                this.TestThread(t.ToString());
                mre.Set();
            };

            ThreadPool.QueueUserWorkItem(method, "TestManualResetEvent");

            Console.WriteLine("我们来干点别的。。。。");
            Console.WriteLine("我们来干点别的。。。。");
            Console.WriteLine("我们来干点别的。。。。");
            Console.WriteLine("我们来干点别的。。。。");
            mre.WaitOne();

            //ManualResetEvent mre = new ManualResetEvent(false);
            //new Action(() =>
            //{
            //    Thread.Sleep(5000);
            //    Console.WriteLine("委托的异步调用");
            //    mre.Set();//打开
            //}).BeginInvoke(null, null);

            //mre.WaitOne();
            //Console.WriteLine("12345");
            //mre.Reset();//关闭
            //new Action(() =>
            //{
            //    Thread.Sleep(5000);
            //    Console.WriteLine("委托的异步调用2");
            //    mre.Set();//打开
            //}).BeginInvoke(null, null);
            //mre.WaitOne();
            //Console.WriteLine("23456");


            //ThreadPool.SetMaxThreads(8, 8);//最小也是核数
            //ThreadPool.SetMinThreads(8, 8);
            //int workerThreads;
            //int ioThreads;
            //ThreadPool.GetMaxThreads(out workerThreads, out ioThreads);
            //Console.WriteLine(String.Format("Max worker threads: {0};    Max I/O threads: {1}", workerThreads, ioThreads));

            //ThreadPool.GetMinThreads(out workerThreads, out ioThreads);
            //Console.WriteLine(String.Format("Min worker threads: {0};    Min I/O threads: {1}", workerThreads, ioThreads));

            //ThreadPool.GetAvailableThreads(out workerThreads, out ioThreads);
            //Console.WriteLine(String.Format("Available worker threads: {0};    Available I/O threads: {1}", workerThreads, ioThreads));
            watch.Stop();
            Console.WriteLine("**********************btnThreadPool_Click   End 主线程id {0} {1}************************************", Thread.CurrentThread.ManagedThreadId, watch.ElapsedMilliseconds);
            Console.WriteLine();
        }
Example #45
0
 /// <summary>带异常处理的线程池任务调度</summary>
 /// <param name="callback"></param>
 /// <param name="state"></param>
 public static void QueueUserWorkItem(WaitCallback callback, Object state)
 {
     QueueUserWorkItem(callback, state, ex => XTrace.Log.Debug(null, ex));
 }
Example #46
0
        public unsafe void Draw(Surface dst, Matrix transform, ResamplingAlgorithm sampling)
        {
            if (this.disposed)
            {
                throw new ObjectDisposedException("MaskedSurface");
            }

            if (this.surface == null || !transform.IsInvertible)
            {
                return;
            }

            PdnRegion theRegion;
            Rectangle regionBounds;

            if (this.path == null)
            {
                theRegion    = this.region.Clone();
                regionBounds = this.region.GetBoundsInt();
                theRegion.Transform(transform);
            }
            else
            {
                using (PdnGraphicsPath mPath = this.shadowPath.Clone())
                {
                    regionBounds = Rectangle.Truncate(mPath.GetBounds());
                    mPath.Transform(transform);
                    theRegion = new PdnRegion(mPath);
                }
            }

            DrawContext dc = new DrawContext();

            dc.boundsX = regionBounds.X;
            dc.boundsY = regionBounds.Y;

            Matrix inverse = transform.Clone();

            inverse.Invert();

            dc.inverses = new Matrix[Processor.LogicalCpuCount];
            for (int i = 0; i < dc.inverses.Length; ++i)
            {
                dc.inverses[i] = inverse.Clone();
            }

            // change in source-[X|Y] w.r.t. destination-[X|Y]
            PointF[] pts = new PointF[] {
                new PointF(1, 0),
                new PointF(0, 1)
            };

            inverse.TransformVectors(pts);
            inverse.Dispose();
            inverse = null;

            dc.dsxddx = pts[0].X;

            if (Math.Abs(dc.dsxddx) > fp_MaxValue)
            {
                dc.dsxddx = 0.0f;
            }

            dc.dsyddx = pts[0].Y;

            if (Math.Abs(dc.dsyddx) > fp_MaxValue)
            {
                dc.dsyddx = 0.0f;
            }

            dc.dsxddy = pts[1].X;

            if (Math.Abs(dc.dsxddy) > fp_MaxValue)
            {
                dc.dsxddy = 0.0f;
            }

            dc.dsyddy = pts[1].Y;

            if (Math.Abs(dc.dsyddy) > fp_MaxValue)
            {
                dc.dsyddy = 0.0f;
            }

            dc.fp_dsxddx = (int)(dc.dsxddx * fp_MultFactor);
            dc.fp_dsyddx = (int)(dc.dsyddx * fp_MultFactor);
            dc.fp_dsxddy = (int)(dc.dsxddy * fp_MultFactor);
            dc.fp_dsyddy = (int)(dc.dsyddy * fp_MultFactor);

            dc.dst = dst;
            dc.src = this.surface;
            Rectangle[] scans = theRegion.GetRegionScansReadOnlyInt();

            if (scans.Length == 1)
            {
                dc.dstScans = new Rectangle[Processor.LogicalCpuCount];
                Utility.SplitRectangle(scans[0], dc.dstScans);
            }
            else
            {
                dc.dstScans = scans;
            }

            WaitCallback wc;

            switch (sampling)
            {
            case ResamplingAlgorithm.NearestNeighbor:
                wc = new WaitCallback(dc.DrawScansNearestNeighbor);
                break;

            case ResamplingAlgorithm.Bilinear:
                wc = new WaitCallback(dc.DrawScansBilinear);
                break;

            default:
                throw new System.ComponentModel.InvalidEnumArgumentException();
            }

            for (int i = 0; i < Processor.LogicalCpuCount; ++i)
            {
                if (i == Processor.LogicalCpuCount - 1)
                {
                    // Don't queue the last work item into a separate thread
                    wc(BoxedConstants.GetInt32(i));
                }
                else
                {
                    threadPool.QueueUserWorkItem(wc, BoxedConstants.GetInt32(i));
                }
            }

            threadPool.Drain();

            for (int i = 0; i < Processor.LogicalCpuCount; ++i)
            {
                dc.inverses[i].Dispose();
                dc.inverses[i] = null;
            }

            dc.src = null;

            theRegion.Dispose();
            theRegion = null;
        }
Example #47
0
 /// <summary>把用户工作项放入队列。指定任务被取消时执行的方法,该方法仅针对尚未被线程开始调用时的任务有效</summary>
 /// <param name="method">任务方法</param>
 /// <param name="abortMethod">任务被取消时执行的方法</param>
 /// <param name="argument">任务参数</param>
 /// <returns>任务编号</returns>
 public Int32 Queue(WaitCallback method, WaitCallback abortMethod, Object argument)
 {
     return(Queue(new ThreadTask(method, abortMethod, argument)));
 }
Example #48
0
 /// <summary>带异常处理的线程池任务调度</summary>
 /// <param name="callback"></param>
 public static void QueueUserWorkItem(WaitCallback callback)
 {
     QueueUserWorkItem(callback, null);
 }
Example #49
0
        public static void Main(string[] args)
        {
            var ts = new ThreadState();

            WaitCallback notifyMsg = state =>
            {
                while (ts.Enabled || _msgQ.Count > 0)
                {
                    Thread.Sleep(500);

                    if (_msgQ.Count > 0)
                    {
                        var msg = (NfMessage)_msgQ.Dequeue();
            #if NOTIFY
                        var nf = new Notification(msg.Summary, msg.Body, msg.Icon);
                        nf.AddHint("append", "allowed");
                        nf.Show();
            #else
                        Console.WriteLine("{0}: {1}", msg.Summary, msg.Body);
            #endif
                    }
                }

                ts.Notification.Set();
            };

            ThreadPool.QueueUserWorkItem(notifyMsg);

            using (var ws = new WebSocket("ws://echo.websocket.org"))
            //using (var ws = new WebSocket("wss://echo.websocket.org"))
            //using (var ws = new WebSocket("ws://localhost:4649"))
            //using (var ws = new WebSocket("ws://localhost:4649/Echo"))
            //using (var ws = new WebSocket("wss://localhost:4649/Echo"))
            //using (var ws = new WebSocket("ws://localhost:4649/Echo?name=nobita"))
            //using (var ws = new WebSocket("ws://localhost:4649/エコー?name=のび太"))
            //using (var ws = new WebSocket("ws://localhost:4649/Chat"))
            //using (var ws = new WebSocket("ws://localhost:4649/Chat?name=nobita"))
            //using (var ws = new WebSocket("ws://localhost:4649/チャット?name=のび太"))
            {
                ws.OnOpen += (sender, e) =>
                {
                    ws.Send("Hi, all!");
                };

                ws.OnMessage += (sender, e) =>
                {
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        enNfMessage("[WebSocket] Message", e.Data, "notification-message-im");
                    }
                };

                ws.OnError += (sender, e) =>
                {
                    enNfMessage("[WebSocket] Error", e.Message, "notification-message-im");
                };

                ws.OnClose += (sender, e) =>
                {
                    enNfMessage(
                        String.Format("[WebSocket] Close({0})", e.Code),
                        e.Reason,
                        "notification-message-im");
                };

        #if DEBUG
                ws.Log.Level = LogLevel.TRACE;
        #endif
                //ws.Compression = CompressionMethod.DEFLATE;
                //ws.Origin = "http://echo.websocket.org";
                //ws.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
                //{
                //  ws.Log.Debug(String.Format("\n{0}\n{1}", certificate.Issuer, certificate.Subject));
                //  return true;
                //};
                //ws.SetCookie(new Cookie("nobita", "\"idiot, gunfighter\""));
                //ws.SetCookie(new Cookie("dora", "tanuki"));
                //ws.SetCredentials ("nobita", "password", false);
                ws.Connect();
                //ws.ConnectAsync();
                //Console.WriteLine("Compression: {0}", ws.Compression);

                Thread.Sleep(500);
                Console.WriteLine("\nType \"exit\" to exit.\n");

                string data;
                while (true)
                {
                    Thread.Sleep(500);

                    Console.Write("> ");
                    data = Console.ReadLine();
                    if (data == "exit")
                    //if (data == "exit" || !ws.IsAlive)
                    {
                        break;
                    }

                    ws.Send(data);
                }
            }

            ts.Enabled = false;
            ts.Notification.WaitOne();
        }
Example #50
0
 /// <summary>把用户工作项放入队列</summary>
 /// <param name="method">任务方法</param>
 /// <returns>任务编号</returns>
 public Int32 Queue(WaitCallback method)
 {
     return(Queue(method, null));
 }
Example #51
0
 public static bool QueueUserWorkItem(WaitCallback callback, object state, bool cancelOnLevelLoaded)
 {
     return(EnqueueTask(callback, state, cancelOnLevelLoaded));
 }
Example #52
0
 public TaskInfo(WaitCallback callback, object state, bool cancellable)
 {
     this.Callback    = callback;
     this.State       = state;
     this.Cancellable = cancellable;
 }
Example #53
0
 public static bool QueueUserWorkItem(WaitCallback callback)
 {
     return(EnqueueTask(callback, null, false));
 }
Example #54
0
 public static bool QueueUserWorkItem(WaitCallback callback, object state)
 {
     return(EnqueueTask(callback, state, false));
 }
Example #55
0
 /// <summary>
 ///
 /// </summary>
 public void InitializeSound(System.Windows.Media.Color color, WaitCallback cb)
 {
     _audio.InitializeSound(_camera.Sensor, color);
     _audio.callback = cb;
 }
Example #56
0
 /// <summary>
 /// Initialize the callback holding object.
 /// </summary>
 /// <param name="callback">Callback delegate for the callback.</param>
 /// <param name="state">State with which to call the callback delegate.</param>
 public WaitingCallback(WaitCallback callback, object state)
 {
     Callback = callback;
     State    = state;
 }
Example #57
0
 /// <summary>
 /// 把执行操作放到队列中。当线程池的线程可用的时候,方法执行。
 /// </summary>
 /// <param name="callback">一个代表将要执行方法的WaitCallback对象</param>
 public static WorkItem QueueUserWorkItem(WaitCallback callback)
 {
     return(QueueUserWorkItem(callback, null));
 }
Example #58
0
 protected abstract AsyncCompletionResult StartWritingBufferedMessage(Message message, ArraySegment <byte> messageData, bool allowOutputBatching, TimeSpan timeout, WaitCallback callback, object state);
Example #59
0
 /// <summary>
 /// 把执行方法放到队列中,并指定了一个对象,它包含使用该方法的数据。
 /// 当线程池线程变为可用的时候,方法执行。
 /// </summary>
 /// <param name="callBack">工作项(WaitCallback)对象</param>
 /// <param name="threadName">线程名称,最长不超过10个字符!</param>
 /// <param name="priority">线程优先级</param>
 public static bool Queue(WaitCallback callBack, string threadName, ThreadPriority priority)
 {
     return(Queue(callBack, threadName, null, priority));
 }
Example #60
0
        private void method_8(int int_4)
        {
            WaitCallback waitCallback = null;
            AudioStatus  @enum        = this.enum1_0;

            if (@enum == AudioStatus.IsCurrentlyPlayingAudio)
            {
                this.StopPlaying();
            }
            lock (this.object_0)
            {
                Stream arg_35_0 = this.stream1_0;
                this.int_3        = int_4;
                arg_35_0.Position = (long)int_4;
                if (@enum == AudioStatus.ShouldStartAudio)
                {
                    int   count = this.queue_0.Count;
                    float num   = 1f / ((float)(this.int_0 * count) / (float)this.GetWaveFormat().short_1);
                    float num2  = 0f;
                    float num3  = 1f;
                    if (this.GetWaveFormat().waveFormatTag_0 == WaveFormatTag.IEEEFloat)
                    {
                        float[] array = new float[this.int_0 >> 2];
                        using (Queue <Class158> .Enumerator enumerator = this.queue_0.GetEnumerator())
                        {
                            while (enumerator.MoveNext())
                            {
                                Class158 current = enumerator.Current;
                                float[]  array2  = current.method_3().method_1();
                                int      num4    = this.stream1_0.vmethod_4(array, 0, array.Length);
                                if (num4 == 0)
                                {
                                    break;
                                }
                                int i    = 0;
                                int num5 = 0;
                                while (i < num4)
                                {
                                    array2[i] = num3 * array2[i] + num2 * array[i];
                                    num5++;
                                    if (num5 == (int)this.GetWaveFormat().short_0)
                                    {
                                        num2 += num;
                                        num3 -= num;
                                        num5  = 0;
                                    }
                                    i++;
                                }
                                Array.Clear(array2, num4, current.method_3().method_5() - num4);
                                current.method_3().method_6(num4);
                            }
                            goto IL_27D;
                        }
                    }
                    if (this.GetWaveFormat().waveFormatTag_0 == WaveFormatTag.PCM)
                    {
                        using (Class19 @class = new Class19(this.int_0))
                        {
                            foreach (Class158 current2 in this.queue_0)
                            {
                                short[] array3 = current2.method_3().method_2();
                                short[] array4 = Class19.smethod_0(@class);
                                int     num6   = this.stream1_0.vmethod_3(Class19.smethod_1(@class), this.int_0) >> 1;
                                if (num6 == 0)
                                {
                                    break;
                                }
                                int j    = 0;
                                int num7 = 0;
                                while (j < num6)
                                {
                                    array3[j] = (short)(num3 * (float)array3[j] + num2 * (float)array4[j]);
                                    num7++;
                                    if (num7 == (int)this.GetWaveFormat().short_0)
                                    {
                                        num2 += num;
                                        num3 -= num;
                                        num7  = 0;
                                    }
                                    j++;
                                }
                                Array.Clear(array3, num6, current2.method_3().method_7() - num6);
                                current2.method_3().method_8(num6);
                            }
                        }
                    }
IL_27D:
                    GC.Collect();
                    this.stopwatch_0.Reset();
                    this.method_9(0);
                    if (!this.bool_1)
                    {
                        if (waitCallback == null)
                        {
                            waitCallback = new WaitCallback(this.method_12);
                        }
                        ThreadPool.QueueUserWorkItem(waitCallback);
                    }
                }
            }
        }