protected override void OnExecute()
        {
            System.Threading.WaitCallback renderDelegate = new System.Threading.WaitCallback(Render);

            for (int i = 0; i < IterationCount; ++i)
            {
                for (int j = 0; j < this.blitRects.Length; ++j)
                {
                    object jObj = BoxedConstants.GetInt32(j);
                    this.threadPool.QueueUserWorkItem(renderDelegate, jObj);
                }

                this.threadPool.Drain();
            }
        }
        private void ExportSelectedLanguage()
        {
            if (exportSaveFileDialog.ShowDialog() != DialogResult.OK) return;

            string exportFilePath = exportSaveFileDialog.FileName;

            string sourceCulture = ((DropDownListItem)this.lstInstalledLanguages.SelectedItem).Key;

            string targetCulture = null;

            if (rbCreateAutoTranslate.Checked)
            {
                targetCulture = (this.ddlCultures.SelectedItem as DropDownListItem).Key.ToString();
            }

            ExtractionMode mode =
                this.rbCreateAutoTranslate.Checked ? ExtractionMode.WebTranslation
                : this.rbCreateReverse.Checked ? ExtractionMode.Reverse
                : this.rbCreateCopy.Checked ? ExtractionMode.Copy
                : this.rbCreateLegacyEpiDatabase.Checked ? ExtractionMode.DatabaseTranslation
                : this.rbCreateExpansion.Checked ? ExtractionMode.Double
                : mode = ExtractionMode.None;

            string installPath = this.folderBrowserDialog.SelectedPath;

            string languageDbPath = this.txtLanguageDatabase.Text;

            System.Threading.WaitCallback callback = new System.Threading.WaitCallback(this.QueueExctractionWorkerThread);

            object[] args = new object[6];
            args[0] = installPath;
            args[1] = sourceCulture;
            args[2] = targetCulture;
            args[3] = mode;
            args[4] = exportFilePath;
            args[5] = languageDbPath;

            System.Threading.ThreadPool.QueueUserWorkItem(callback, (object)args);
        }
        private void ReloadOneTab(Object arg)
        {
            BrowserTab tab        = arg as BrowserTab;
            int        retryLevel = 0;

            if (tab == null)
            {
                Object[] a = arg as Object[];
                tab        = a[0] as BrowserTab;
                retryLevel = (int)a[1];
            }

            try
            {
                tab.ComObject.Refresh2(RefreshLevel.Completely);
            }
            catch (System.Runtime.InteropServices.COMException cexc1)
            {
                // This can happen if IE cannot refresh. For instance if
                // there's been a Javascript exception and IE is prompting
                // the user to debug the page, with a modal prompt. It can
                // also happen if IE is busy, already refreshing and
                // waiting for a response.

                uint hresult = (uint)System.Runtime.InteropServices.Marshal.GetHRForException(cexc1);
                // sleep and retry here, if IE is busy.
                // HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER)
                if (hresult == 0x8001010AU)
                {
                    var msg = String.Format("Refreshing {0} failed, exception: {1:8X}, {2}",
                                            tab.LocationUrl, hresult,
                                            (retryLevel < ReloadRetryLimit) ? "will retry" : "giving up");
                    AddAlert(msg);

                    if (retryLevel < ReloadRetryLimit)
                    {
                        var waitAndRetry = new System.Threading.WaitCallback(obj => {
                            System.Threading.Thread.Sleep(1000);     // in ms
                            Object[] args = { obj, retryLevel + 1 };
                            ReloadOneTab(args);
                        });
                        System.Threading.ThreadPool.QueueUserWorkItem(waitAndRetry, tab);
                    }
                }
                else
                {
                    var msg = String.Format("Refreshing {0} failed: exception: {1:8X}",
                                            tab.LocationUrl, hresult);
                    AddAlert(msg);
                }
            }
        }
Exemple #4
0
        void GetPageList(int pIndex)
        {
            int index = pIndex;

            if (index < 1)
            {
                index = 1;
            }
            if (index > this.pager.PageCount)
            {
                index = this.pager.PageCount;
            }

            int skip = index * PageSize - PageSize;
            int take = this.iCount - skip;

            if (take > PageSize)
            {
                take = PageSize;
            }
            if (take == 0)
            {
                take = PageSize;
            }

            System.Threading.WaitCallback callBack = (state) =>
            {
                var v2 = this.vList.Skip(skip).Take(take);

                try
                {
                    moduleList = v2.ToList();
                }
                catch (System.Exception exc)
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        EAS.Controls.Window.HideLoading();
                        MessageBox.Show("请求数据时发生错误:" + exc.Message, "错误", MessageBoxButton.OK);
                    });
                    return;
                }

                Dispatcher.BeginInvoke(() =>
                {
                    EAS.Controls.Window.HideLoading();
                    this.dataList.ItemsSource = moduleList;
                });
            };

            System.Threading.ThreadPool.QueueUserWorkItem(callBack);
        }
Exemple #5
0
        internal static void DoTrace(Action <ITrace> execute)
        {
            System.Threading.WaitCallback waitCallback = new System.Threading.WaitCallback((o) =>
            {
                ITrace trace = IoC.Resolve <ITrace>();
                if (trace != null)
                {
                    execute(trace);
                }
            });

            waitCallback(null);
        }
        public static System.Threading.ManualResetEvent WaitableQueueUserWorkItem(WaitCallback callback)
        {
            var waitObject = new System.Threading.ManualResetEvent(false);

            if (!QueueUserWorkItem((o) =>
            {
                callback(o);
                waitObject.Set();
            }))
            {
                return(null);
            }
            return(waitObject);
        }
        protected override void OnExecute()
        {
            System.Threading.WaitCallback renderDelegate = new System.Threading.WaitCallback(Render);

            for (int i = 0; i < IterationCount; ++i)
            {
                for (int j = 0; j < BlitRects.Length; ++j)
                {
                    object jObj = BoxedConstants.GetInt32(j);
                    ThreadPool.QueueUserWorkItem(renderDelegate, jObj);
                }

                ThreadPool.Drain();
            }
        }
Exemple #8
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //1.启动升级。
            System.Threading.WaitCallback callBack = (s) =>
            {
                EAS.WinClient.Application.Upgrade();
            };
            System.Threading.ThreadPool.QueueUserWorkItem(callBack);

            //2.启动平台。
            EAS.WinClient.Application.Start();
        }
Exemple #9
0
        private void ImportLanguage(string applicationPath)
        {
            string tableName     = lvDataSourceObjects.SelectedItems[0].Text;
            string targetCulture = (ddlCultures.SelectedItem as DropDownListItem).Key.ToString();
            string installPath   = applicationPath;

            System.Threading.WaitCallback callback = new System.Threading.WaitCallback(this.QueueInstallLanguageWorkerThread);

            object[] args = new object[4];
            args[0] = installPath;
            args[1] = targetCulture;
            args[2] = selectedDataSource;
            args[3] = tableName;

            System.Threading.ThreadPool.QueueUserWorkItem(callback, (object)args);
        }
Exemple #10
0
        /// <summary>
        /// 点击按钮,并监听新窗口。
        /// </summary>
        /// <param name="button"></param>
        /// <param name="parentWnd"></param>
        /// <param name="callback">点击按钮后执行的查找新窗口回调方法。</param>
        /// <param name="value">传递给查找新窗口回调方法的值。</param>
        /// <returns></returns>
        public static bool ClickButton(IntPtr button, IntPtr parentWnd, System.Threading.WaitCallback callback, object value)
        {
            NativeApi.SwitchToThisWindow(parentWnd, true);
            NativeApi.SendMessage(button, WMMSG.WM_SETFOCUS, 0, 0);
            if (callback != null)
            {
                System.Threading.ThreadPool.QueueUserWorkItem(callback, value);
            }
            IntPtr result1 = NativeApi.SendMessage(button, WMMSG.BM_CLICK, 0, 0);

            //IntPtr result1 = NativeApi.SendMessage(button, WMMSG.WM_LBUTTONDOWN, MouseVirtualKeys.None, 0);
            //System.Threading.Thread.Sleep(10);
            //IntPtr result2 = NativeApi.SendMessage(button, WMMSG.WM_LBUTTONUP, MouseVirtualKeys.None, 0);
            //return result1 == IntPtr.Zero && result2 == IntPtr.Zero;
            return(result1 == IntPtr.Zero);
        }
Exemple #11
0
        static StackObject *QueueUserWorkItem_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Threading.WaitCallback @callBack = (System.Threading.WaitCallback) typeof(System.Threading.WaitCallback).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 8);
            __intp.Free(ptr_of_this_method);


            var result_of_this_method = System.Threading.ThreadPool.QueueUserWorkItem(@callBack);

            __ret->ObjectType = ObjectTypes.Integer;
            __ret->Value      = result_of_this_method ? 1 : 0;
            return(__ret + 1);
        }
Exemple #12
0
        /// <summary>
        /// 异步请求HTTP POST
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="data">普通表单项(非二进制)</param>
        /// <param name="byteData">二进制数据(通常指附件)</param>
        /// <param name="byteDataFileNames">二进制数据对应的文件名(通常指附件)</param>
        /// <param name="isGZip">是否压缩数据(只针对二进制而言)</param>
        /// <param name="dataEncoding">发送和读取数据的编码</param>
        /// <param name="timeoutMillisecond">超时时间(单位:毫秒)</param>
        /// <param name="requestCookies">提交的cookie集合</param>
        /// <param name="invokeObject">回调函数的调用对象</param>
        /// <param name="callBackHandle">回调</param>
        /// <param name="evData">回调附加的传递参数</param>
        /// <returns></returns>
        public static HttpWebRequest AsynPost(string url, IDictionary <string, string> data
                                              , IDictionary <string, byte[]> byteData, IDictionary <string, string> byteDataFileNames, bool isGZip, Encoding dataEncoding, int timeoutMillisecond
                                              , CookieCollection requestCookies
                                              , System.ComponentModel.ISynchronizeInvoke invokeObject, HttpAccessAsynCallBack callBackHandle, Object evData)
        {
            HttpWebRequest request = GetHttpPostRequest(url, data, byteData, byteDataFileNames, isGZip, dataEncoding, timeoutMillisecond, requestCookies);

            System.Collections.ArrayList poD = new System.Collections.ArrayList();
            poD.Add(request);
            poD.Add(invokeObject);
            poD.Add(callBackHandle);

            System.Threading.WaitCallback edGetResponseCallB = new System.Threading.WaitCallback(delegate(object poData) {
                System.Collections.ArrayList pD = (System.Collections.ArrayList)poData;
                HttpWebRequest req = (HttpWebRequest)pD[0];
                System.ComponentModel.ISynchronizeInvoke invObj = (System.ComponentModel.ISynchronizeInvoke)pD[1];
                HttpAccessAsynCallBack callB = (HttpAccessAsynCallBack)pD[2];

                HttpWebResponse response = null;
                try {
                    response = (HttpWebResponse)req.GetResponse();
                } catch (Exception ex) {
                    //如果强制被取消的话,就抛错.所以错了就不调用了
                    invObj.Invoke(callB
                                  , new Object[] {
                        null
                        , null
                        , ex
                        , evData
                    });
                    return;
                }
                invObj.Invoke(callB
                              , new Object[] {
                    response
                    , GetCookiesByHeaderSetCookie(response)
                    , null
                    , evData
                });
            });

            System.Threading.ThreadPool.QueueUserWorkItem(edGetResponseCallB, poD);

            return(request);
        }
Exemple #13
0
        static void Main(string[] args)
        {
            // setting threadpool
            //System.Threading.ThreadPool.SetMinThreads(1, 1);
            //System.Threading.ThreadPool.SetMaxThreads(4, 4);

            List <AlgBase> algorithms = new List <AlgBase>();

            algorithms.Add(new Algorithm1("test1"));
            algorithms.Add(new Algorithm2("test2"));
            algorithms.Add(new Algorithm3("test3"));
            algorithms.Add(new Algorithm1("test4"));
            algorithms.Add(new Algorithm2("test5"));
            algorithms.Add(new Algorithm3("test6"));
            algorithms.Add(new Algorithm1("test7"));
            algorithms.Add(new Algorithm2("test8"));

            eventX.Reset();
            System.Threading.WaitCallback workUnit = new System.Threading.WaitCallback(ExecuteAlgorithm);
            foreach (AlgBase alg in algorithms)
            {
                lock (mMutex)
                {
                    mAmountOfItem++;
                }
                object[] param = new object[2] {
                    alg, 0
                };
                System.Threading.ThreadPool.QueueUserWorkItem(workUnit, param);
            }

            if (eventX.WaitOne(7000, true) == false)
            {
                Console.WriteLine($"{System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")}: Have one timeout!");
            }
            else
            {
                Console.WriteLine("all back");
            }

            eventX.Reset();
            Console.ReadLine();
        }
        public static void Spawn(uint npcid, byte map, float x, float y, float z)
        {
            Zone zone;

            if (Singleton.Zones.TryGetZone(map, out zone))
            {
                MapObject regionObject = null;
                System.Threading.WaitCallback callback = delegate(object state)
                {
                    Singleton.Templates.UnspawnInstance(regionObject);
                    GC.Collect(0, GCCollectionMode.Optimized);
                };

                if (Singleton.Templates.SpawnNpcInstance(npcid, new Point(x, y, z), new Rotator(0, 0), zone, false, out regionObject))
                {
                    QueedTask timer = new QueedTask(callback, regionObject, 300000);
                }
            }
        }
        private void ExportSelectedLanguage()
        {
            if (exportSaveFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            string exportFilePath = exportSaveFileDialog.FileName;

            string sourceCulture = ((DropDownListItem)this.lstInstalledLanguages.SelectedItem).Key;

            string targetCulture = null;

            if (rbCreateAutoTranslate.Checked)
            {
                targetCulture = (this.ddlCultures.SelectedItem as DropDownListItem).Key.ToString();
            }


            ExtractionMode mode =
                this.rbCreateAutoTranslate.Checked ? ExtractionMode.WebTranslation
                : this.rbCreateReverse.Checked ? ExtractionMode.Reverse
                : this.rbCreateCopy.Checked ? ExtractionMode.Copy
                : this.rbCreateLegacyEpiDatabase.Checked ? ExtractionMode.DatabaseTranslation
                : this.rbCreateExpansion.Checked ? ExtractionMode.Double
                : mode = ExtractionMode.None;

            string installPath = this.folderBrowserDialog.SelectedPath;

            string languageDbPath = this.txtLanguageDatabase.Text;

            System.Threading.WaitCallback callback = new System.Threading.WaitCallback(this.QueueExctractionWorkerThread);

            object[] args = new object[6];
            args[0] = installPath;
            args[1] = sourceCulture;
            args[2] = targetCulture;
            args[3] = mode;
            args[4] = exportFilePath;
            args[5] = languageDbPath;

            System.Threading.ThreadPool.QueueUserWorkItem(callback, (object)args);
        }
 private void StartCameraInternal(CameraInfo cam)
 {
     System.Threading.WaitCallback action = delegate
     {
         try
         {
             if (cam.Provider == CameraProvider.Sanyo)
             {
                 this._mainForm.StartRecord(cam);
             }
         }
         catch (System.Net.WebException ex)
         {
             var msg = string.Format("无法连接 {0}", cam.Location.Host);
             _mainForm.ShowMessage(msg);
         }
     };
     System.Threading.ThreadPool.QueueUserWorkItem(action);
 }
Exemple #17
0
        private void btnNew_Click(object sender, EventArgs e)
        {
            SaveFileDialog exportSaveFileDialog = new SaveFileDialog();

            exportSaveFileDialog.Filter = "Microsoft Access File | *.mdb";
            if (exportSaveFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            string exportFilePath = exportSaveFileDialog.FileName;

            string sourceCulture;

            if (lbxLanguages.SelectedItem != null)
            {
                sourceCulture = ((DropDownListItem)lbxLanguages.SelectedItem).Key;
            }
            else
            {
                sourceCulture = ((DropDownListItem)lbxLanguages.Items[0]).Key;
            }

            string targetCulture = null;

            ExtractionMode mode = ExtractionMode.None;

            string installPath = Path.GetDirectoryName(Application.ExecutablePath);

            string languageDbPath = string.Empty;

            System.Threading.WaitCallback callback = new System.Threading.WaitCallback(this.QueueExctractionWorkerThread);

            object[] args = new object[6];
            args[0] = installPath;
            args[1] = sourceCulture;
            args[2] = targetCulture;
            args[3] = mode;
            args[4] = exportFilePath;
            args[5] = languageDbPath;

            System.Threading.ThreadPool.QueueUserWorkItem(callback, (object)args);
        }
        /// <summary>
        /// This function starts up and keeps running indefinatly, constantly listening and putting incoming connections in the 'to process' threadpool. (do not run this in your mainthread, as this is a BLOCKING function, indefinatly)
        /// </summary>
        /// <param name="CallBack">The callback of the function that we want to use to process incoming connections.</param>
        public void Listen(System.Threading.WaitCallback CallBack)
        {
            try
            {
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //Prepare the info for the socket that we want to listen on
                socket.Bind(new IPEndPoint(IPAddress.Any, _Port));                                           //Bind the socket to a port and a possible range of IPAdresses (will only react to IP's from this range)
                socket.Listen(_BackLogQueue);                                                                //Start the listening

                while (true)                                                                                 //Continually listen and dispatch incomming messages.
                {
                    Socket client = socket.Accept();                                                         //Accept the connection if we detect a request
                    System.Threading.ThreadPool.QueueUserWorkItem(CallBack, client);                         //Dispatch the connection - see HandleRequest function for how we process a connection.
                }
            }
            catch (Exception e)
            {
                //If an error happens; write it to the logfile.
                LogError(e, "LogServer.txt");
            }
        }
            private void RunDelegateAsync(Delegate method, object[] args)
            {
                System.Threading.WaitCallback del = delegate(object unused)
                {
                    try
                    {
                        object temp = method.DynamicInvoke(args);
                        System.Threading.Interlocked.Exchange(ref m_return, temp);
                    }
                    catch (Exception ex)
                    {
                        System.Threading.Interlocked.Exchange(ref m_exception, ex);
                    }

                    System.Threading.Interlocked.Exchange(ref m_completed, 1);
                    m_handle.Set();
                };

                System.Threading.ThreadPool.QueueUserWorkItem(del);
            }
Exemple #20
0
        void DownUpdateConfig()
        {
            System.Threading.WaitCallback callBack = (state) =>
            {
                //Uri url = new Uri(System.Windows.Application.Current.Host.Source, "slupdate.xml");
                Uri       url    = new Uri("slupdate.xml", UriKind.Relative);
                WebClient client = new WebClient();
                System.Threading.Tasks.Task <Stream> task = client.OpenReadTaskAsync(url);
                task.Wait();

                if (task.Exception != null)
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("读升级参数出错:" + task.Exception, "错误", MessageBoxButton.OK);
                        return;
                    });
                }

                using (var sw = new System.IO.StreamReader(task.Result))
                {
                    string xml = sw.ReadToEnd();
                    task.Result.Close();

                    try
                    {
                        SLContext.Instance.UpdateXml = SmartConfig.LoadXML(xml);
                    }
                    catch { }
                }

                Dispatcher.BeginInvoke(() =>
                {
                    this.loaderControl.Initialize();
                });
            };

            //X.线程同步。
            System.Threading.ThreadPool.QueueUserWorkItem(callBack);
        }
Exemple #21
0
        void LoadDataList()
        {
            string key = this.tbSeach.Text.Trim();

            System.Threading.WaitCallback callBack = (state) =>
            {
                using (DbEntities db = new DbEntities())
                {
                    var v = from c in db.Modules
                            where c.Assembly.StartsWith(key) || c.Type.StartsWith(key) || c.Developer.StartsWith(key)
                            select c;
                    this.vList = v as IQueryable <Module>;

                    try
                    {
                        this.iCount = v.Count();
                    }
                    catch (System.Exception exc)
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show("请求数据时发生错误:" + exc.Message, "错误", MessageBoxButton.OK);
                        });
                        return;
                    }

                    Dispatcher.BeginInvoke(() =>
                    {
                        int mod              = iCount % PageSize;
                        int pages            = mod == 0 ? iCount / PageSize : (iCount / PageSize) + 1;
                        this.pager.PageCount = pages;
                        this.pager.ReBind(pages);
                        this.GetPageList(1);
                    });
                }
            };

            System.Threading.ThreadPool.QueueUserWorkItem(callBack);
        }
Exemple #22
0
        private void ImportLanguage(string applicationPath)
        {
            string tableName = lvDataSourceObjects.SelectedItems[0].Text;
            string targetCulture = (ddlCultures.SelectedItem as DropDownListItem).Key.ToString();
            string installPath = applicationPath;

            System.Threading.WaitCallback callback = new System.Threading.WaitCallback(this.QueueInstallLanguageWorkerThread);

            object[] args = new object[4];
            args[0] = installPath;
            args[1] = targetCulture;
            args[2] = selectedDataSource;
            args[3] = tableName;

            System.Threading.ThreadPool.QueueUserWorkItem(callback, (object)args);
        }
 public static bool QueueUserWorkItem(System.Threading.WaitCallback callBack) => throw null;
        private void MultiThreadProcess()
        {
            try
            {
                int qty = data.Count;
                if (data != null && qty > 0)
                {
                    System.Threading.WaitCallback callback = new System.Threading.WaitCallback(SendToAlarmServerWorkThread);
                    if (qty <= OnceSendDataQty)
                    {
                        List<GPSDataEntity> ds = new List<GPSDataEntity>(data);
                        System.Threading.ThreadPool.QueueUserWorkItem(callback, ds);
                    }
                    else
                    {
                        double page = System.Math.Ceiling((double)qty / OnceSendDataQty);
                        PES.Beehive.Logging.Logger.Trace("在线程池启动工作线程,报警数据将拆分为" + page + "次发送,每次发送" + OnceSendDataQty + "条");

                        //计时
                        //timer = new PES.GPSGateway.Business.Database.MultipleThreadTimer("报警数据转发");
                        //timer.StartTimer(qty, (int)page);

                        List<GPSDataEntity> gs = new List<GPSDataEntity>();
                        for (int i = 0; i < page; i++)
                        {
                            gs = new List<GPSDataEntity>();
                            for (int j = 0; j < OnceSendDataQty; j++)
                            {
                                int index = i * OnceSendDataQty + j;
                                if (index >= qty)
                                    break;
                                gs.Add(data[index]);
                            }
                            List<GPSDataEntity> ds = new List<GPSDataEntity>(gs);
                            System.Threading.ThreadPool.QueueUserWorkItem(callback, ds);
                        }
                    }
                    base.Process();
                }
            }
            catch (Exception ex)
            {
                PES.Beehive.Logging.Logger.Trace("Process报警数据转发失败");
                PES.Beehive.Logging.Logger.Error(ex, null);
            }
        }
Exemple #25
0
 public static bool QueueUserWorkItem(System.Threading.WaitCallback callBack, object state)
 {
     return(default(bool));
 }
Exemple #26
0
 public static void EnqueueToThreadPool(this Action action)
 {
     System.Threading.WaitCallback callback = state => action();
     System.Threading.ThreadPool.QueueUserWorkItem(callback);
 }
 /// <summary>
 /// Sends the work process to the ThreadPool for starting when resources are available, 
 /// This needs to initialize the WaitCallback with the Run function.
 /// </summary>
 /// <param name="backgroundThread">Not Used.</param>
 /// <param name="priority">Not Used.</param>
 public override void Start(bool backgroundThread, System.Threading.ThreadPriority priority)
 {
     _callback = new System.Threading.WaitCallback (Run);
                 System.Threading.ThreadPool.QueueUserWorkItem (_callback);
 }
 public static bool QueueUserWorkItem(System.Threading.WaitCallback callBack, object state)
 {
     throw null;
 }
Exemple #29
0
 public AsyncHelpersTask(AsyncDelegate asyncDelegate)
 {
     AsyncDelegate = asyncDelegate;
 }
        /// <summary>
        /// 下载配置文件。
        /// </summary>
        void DownSlConfig()
        {
            //A.初始化系统
            System.Threading.WaitCallback callBack = (state) =>
            {
                try
                {
                    EAS.ConfigManager.Current.Load();
                }
                catch (System.Exception exc)
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("读系统配置信息出错:" + exc.Message, "错误", MessageBoxButton.OK);
                    });
                    return;
                }

                Dispatcher.BeginInvoke(() =>
                {
                    this.loaderControl.Text = "系统配置检查完成...";
                    this.loaderControl.Text = "正在加载系统资源...";
                });

                //1.读系统配置。
                string resourceInfo = string.Empty;
                try
                {
                    resourceInfo = EAS.Configuration.Config.GetValue("EAS.Explorer.Resource");
                }
                catch { }

                //2.加载资源。
                try
                {
                    ResourceLoader loader = new ResourceLoader();
                    loader.Load(resourceInfo);
                }
                catch //(System.Exception exc)
                {
                    //Dispatcher.BeginInvoke(() =>
                    //{
                    //    MessageBox.Show("加载系统资源出错:" + exc.Message, "错误", MessageBoxButton.OK);
                    //});
                    //return;
                }

                //3.读系统时间/藏在读资源之中。
                DateTimeClient.Initialize();

                //4.检查独立存储,转向。
                Dispatcher.BeginInvoke(() =>
                {
                    this.loaderControl.Text = "系统资源加载完成...";

                    EAS.SilverlightClient.Application instance = new EAS.SilverlightClient.Application();
                    new ApplicationBridge().SetInstance2(instance);
                    (EAS.SilverlightClient.Application.Instance as EAS.SilverlightClient.Application).AppStart();

                    using (IsolatedStorageFile storeFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        long oldSize = storeFile.Quota;
                        long newSize = 128 * 1024 * 1024;
                        if ((oldSize + (1024 * 1024)) < newSize)
                        {
                            LoginContext.Singleton.IsolatedStorage = true;
                            App.Navigation(PlugContext.LoginForm as UserControl);
                        }
                        else
                        {
                            App.Navigation(new UpdateLoader());
                        }
                    }
                });
            };

            //A.线程程同步。
            System.Threading.ThreadPool.QueueUserWorkItem(callBack);
        }
Exemple #31
0
        /// <summary>
        /// Performs a test that will allocate close to all of the working set for the CLR under default configuration (8 GB) 1,000,000 allocations.
        /// At 50,000 allocations the overhead of the allocated arrays (12b * 50,000(o) = 600,000b) becomes higher than that of the pool itself.
        /// The pool reflects 50% occupancy in such conditions even with lease allocations of 1000b the pool memory is only 192000b
        /// </summary>
        /// <remarks>
        /// Anymore and you will get Fatal Runtime Errors, you used to get OOM but I guess they are removing the obvious in favor of optomizations and domain knowledge.
        /// </remarks>
        public void TestPool()
        {
            Media.Concepts.Classes.Threading.Pool <byte> test = new Media.Concepts.Classes.Threading.Pool <byte>(-1);

            System.Collections.Generic.List <byte[]> allocations = new System.Collections.Generic.List <byte[]>();

            int minimumAllocation = 1000;

            const string Busy = "Busy...";

            System.Threading.WaitCallback workItem = (o) =>
            {
                int size = Utility.Random.Next(minimumAllocation / 100);

                System.Console.WriteLine("Begin Allocation => " + size);

                allocations.Add(test.Rent(size, System.Threading.Thread.CurrentThread));

                System.Console.WriteLine("End Allocation => " + size);
            };

            System.Action notifyAndRead = () =>
            {
                System.Console.WriteLine("Requested Allocation");

                System.Console.WriteLine("Occupancy => " + test.Occupancy);

                System.Console.WriteLine("Size => " + test.Size);

                System.Console.WriteLine("Slots => " + test.Slots);
            };

            while (allocations.Count < minimumAllocation)
            {
                if (System.Threading.ThreadPool.QueueUserWorkItem(workItem))
                {
                    notifyAndRead();
                }
                else
                {
                    System.Console.WriteLine(Busy);
                }
            }

            minimumAllocation *= 10;

            while (allocations.Count < minimumAllocation)
            {
                if (System.Threading.ThreadPool.QueueUserWorkItem(workItem))
                {
                    notifyAndRead();
                }
                else
                {
                    System.Console.WriteLine(Busy);
                }
            }

            minimumAllocation *= 10;

            while (allocations.Count < minimumAllocation)
            {
                if (System.Threading.ThreadPool.QueueUserWorkItem(workItem))
                {
                    notifyAndRead();
                }
                else
                {
                    System.Console.WriteLine(Busy);
                }
            }

            minimumAllocation *= 10;

            while (allocations.Count < minimumAllocation)
            {
                if (System.Threading.ThreadPool.QueueUserWorkItem(workItem))
                {
                    notifyAndRead();
                }
                else
                {
                    System.Console.WriteLine(Busy);
                }
            }

            System.Console.WriteLine("@" + minimumAllocation);
            System.Console.WriteLine("Occupancy => " + test.Occupancy);
            System.Console.WriteLine("Size => " + test.Size);
            System.Console.WriteLine("Slots => " + test.Slots);
        }
 public static void BeginPoolInvoke(System.Threading.WaitCallback Method)
 {
     System.Threading.ThreadPool.QueueUserWorkItem(Method);
 }
        /// <summary>
        /// Attempts to enqueue a method for exection inside the current ThreadPool
        /// </summary>
        /// <param name="action">Representing the method to execute</param>
        /// <param name="state">State object</param>
        /// <returns>True if work item was added to the queue, otherwise false</returns>
        /// <exception cref="ArgumentNullException">Action is null</exception>
        public bool TryRun(System.Threading.WaitCallback action, object state)
        {
            TurboContract.Requires(action != null, conditionString: "action != null");

            return(System.Threading.ThreadPool.QueueUserWorkItem(action, state));
        }
Exemple #34
0
		internal static void TestSndComparer(TestContext tc, BlamVersion game, string dir, string[] map_names)
		{
			int map_count = map_names.Length;
			List<MapSndComparer> maps = new List<MapSndComparer>(map_count);

			var thread_code = new System.Threading.WaitCallback(delegate(object param)
			{
				var args = param as CacheFileOutputInfoArgs;

				MapSndComparer cmp = SndComparerMethod(args);
				lock (maps)
					maps.Add(cmp);

				args.SignalFinished();
			});

			CacheFileOutputInfoArgs.TestThreadedMethod(tc, thread_code,
				game, dir, map_names);

			SndComparer snd_cmp = new SndComparer(map_count);
			snd_cmp.PreProcess(maps, map_count);
			snd_cmp.ScanForDiffs();
			snd_cmp.OutputDiffs(BuildResultPath(kTestResultsPath, game, null, "sound_cmp_results", "txt"));
		}
Exemple #35
0
    public static Texture2D CreateSphericalMapFromCubeMap(Cubemap cubemap)
    {
        int sphericalMapSizeX = 5000;// cubemap.width * 2;
        int sphericalMapSizeY = 2500;// cubemap.height * 1;

        Debug.Log("CubeMap transfer to SphericalMap start");

        Color[][] facePixels = new Color[6][];
        for (int a = 0; a < 6; a++)
        {
            facePixels[a] = cubemap.GetPixels((CubemapFace)a);

            //facePixels[a] = new Color[cubemap.width * cubemap.height];
            //pixels.CopyTo(facePixels[a], 0);
        }

        Color[] sphereColors = null;
        Color32[] sphereColors32 = null;
        if (ThreadProcessData.useColor32)
            sphereColors32 = new Color32[sphericalMapSizeX * sphericalMapSizeY];
        else
            sphereColors = new Color[sphericalMapSizeX * sphericalMapSizeY];

        //Texture2D sphereTex = new Texture2D(sphericalMapSizeX, sphericalMapSizeY, TextureFormat.RGB24, false);

        //for (int a = 0; a < sphereColors.Length; a++)
        //{
        //    sphereColors[a] = Color.red;
        //}

        //I prefer use 1 thread to process at least 1 line on spherical map.
        Debug.Assert(sphericalMapSizeY >= ThreadProcessData.maxThreadAmount);//I don't want to handle sphericalMapSizeY/maxThreadAmount=0

        int eachThreadProcessLine = Mathf.FloorToInt((float)sphericalMapSizeY / (float)ThreadProcessData.maxThreadAmount + 0.5f);
        ThreadProcessData[] threadProcessData = new ThreadProcessData[ThreadProcessData.maxThreadAmount];
        int processLineStart = 1;//start from 1 (not 0)
        int processLineEnd = processLineStart + eachThreadProcessLine - 1;
        for (int a = 0; a < ThreadProcessData.maxThreadAmount; a++)
        {
            threadProcessData[a] = new ThreadProcessData();
            threadProcessData[a].processLineStart = processLineStart;
            threadProcessData[a].processLineEnd = processLineEnd;
            threadProcessData[a].sphericalMapSizeX = sphericalMapSizeX;
            threadProcessData[a].sphericalMapSizeY = sphericalMapSizeY;
            threadProcessData[a].facePixels = facePixels;
            threadProcessData[a].cubemapW = cubemap.width;
            threadProcessData[a].cubemapH = cubemap.height;
            threadProcessData[a].sphereColor = sphereColors;
            threadProcessData[a].sphereColor32 = sphereColors32;

            processLineStart = processLineEnd + 1;
            processLineEnd = processLineStart + eachThreadProcessLine - 1;
            if (processLineEnd > sphericalMapSizeY)
                processLineEnd = sphericalMapSizeY;
        }

        System.Threading.ManualResetEvent[] doneEvents = new System.Threading.ManualResetEvent[threadProcessData.Length];
        int count = 0;
        foreach (ThreadProcessData data in threadProcessData)
        {
            doneEvents[count] = new System.Threading.ManualResetEvent(false);
            data.doneEvent = doneEvents[count];

            System.Threading.WaitCallback waitCallback = new System.Threading.WaitCallback(WorkA);
            System.Threading.ThreadPool.QueueUserWorkItem(waitCallback, data);

            count++;
        }

        // Wait for all threads in pool to calculate.
        System.Threading.WaitHandle.WaitAll(doneEvents);
        Debug.Log("All calculations are complete.");

        //sphereColor
        Texture2D sphereTex = null;
        if (ThreadProcessData.useColor32)
        {
            sphereTex = new Texture2D(sphericalMapSizeX, sphericalMapSizeY, TextureFormat.ARGB32, false);
            sphereTex.SetPixels32(sphereColors32);
        }
        else
        {
            sphereTex = new Texture2D(sphericalMapSizeX, sphericalMapSizeY, TextureFormat.RGB24, false);
            sphereTex.SetPixels(sphereColors);
        }

        //else
        //{
        //    //for (int x = 0; x < sphereTex.width; x++)
        //    //    for (int y = 0; y < sphereTex.height; y++)
        //    //        sphereTex.SetPixel(x, y, Color.black);

        //    for (int x = 0; x < sphericalMapSizeX; x++)
        //    {
        //        for (int y = 0; y < sphericalMapSizeY; y++)
        //        {
        //            Color color;
        //            _processSpherePixel(x, y, sphericalMapSizeX, sphericalMapSizeY, facePixels, cubemap.width, cubemap.height, out color);
        //            sphereTex.SetPixel(x, y, color);
        //        }
        //    }
        //}

        //var bytes = sphereTex.EncodeToJPG();
        //File.WriteAllBytes(Application.dataPath + "/cube2sphere.jpg", bytes);
        //DestroyImmediate(sphereTex);

        Debug.Log("CubeMap transfer to SphericalMap done!!");
        return sphereTex;
    }
Exemple #36
0
 public override TileData GetTile(TiledMapSession.Key key, IMapRenderer renderer, System.Threading.WaitCallback callback, object state)
 {
     if (key == Key.Root && !TileCache.ContainsKey(key))
     {
         TileCache.Add(Key.Root, new TileData(new StandardBitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream("TiledMaps.VirtualEarth.msvesatellite.png"))));
     }
     return(base.GetTile(key, renderer, callback, state));
 }
Exemple #37
0
        private void btnNew_Click(object sender, EventArgs e)
        {
            SaveFileDialog exportSaveFileDialog = new SaveFileDialog();
            exportSaveFileDialog.Filter = "Microsoft Access File | *.mdb";
            if (exportSaveFileDialog.ShowDialog() != DialogResult.OK) return;

            string exportFilePath = exportSaveFileDialog.FileName;

            string sourceCulture;
            if (lbxLanguages.SelectedItem != null)
                sourceCulture = ((DropDownListItem)lbxLanguages.SelectedItem).Key;
            else
                sourceCulture = ((DropDownListItem)lbxLanguages.Items[0]).Key;

            string targetCulture = null;

            ExtractionMode mode = ExtractionMode.None;

            string installPath = Path.GetDirectoryName(Application.ExecutablePath);

            string languageDbPath = string.Empty;

            System.Threading.WaitCallback callback = new System.Threading.WaitCallback(this.QueueExctractionWorkerThread);

            object[] args = new object[6];
            args[0] = installPath;
            args[1] = sourceCulture;
            args[2] = targetCulture;
            args[3] = mode;
            args[4] = exportFilePath;
            args[5] = languageDbPath;

            System.Threading.ThreadPool.QueueUserWorkItem(callback, (object)args);
        }
Exemple #38
0
 /// <summary>
 /// 执行线程异步回调方法
 /// 内部发生异常IIS不受影响
 /// </summary>
 /// <param name="call">异步回调方法</param>
 /// <param name="par">回调方法的传入参数</param>
 public static void RunAsyn(System.Threading.WaitCallback call, object par)
 {
     call.BeginInvoke(par, null, null);
 }
        //计时用,统计多线程效率
        //MultipleThreadTimer timer;
        
        private void SetUseMultiThread(List<PES.GPS.GpsEntityBase.GPSDataEntity> data,int maxSize)
        {
            int qty = data.Count;
            int page = (int)System.Math.Ceiling((double)qty / maxSize);

            //计时用,统计多线程效率
            //经测试,开启计时后会对性能有影响
            //timer = new MultipleThreadTimer("Memcached缓存写入");
            //timer.StartTimer(qty, page);

            List<GPSDataEntity>[] ol = new List<GPSDataEntity>[page];
            List<GPSDataEntity> gs;
            for (int i = 0; i < page; i++)
            {
                gs = new List<GPSDataEntity>();
                for (int j = 0; j < maxSize; j++)
                {
                    int index = i * maxSize + j;
                    if (index >= qty)
                        break;
                    gs.Add(data[index]);
                }
                ol[i] = gs;
            }

            int mt = 1;
            if (mt == 1)
            {
                //1.multi thread
                PES.Beehive.Logging.Logger.Trace("将启动" + page + "个线程来设置Memcached缓存,每个线程处理" + maxSize + "条数据");
                for (int i = 0; i < page; i++)
                {
                    System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(SetData));
                    t.Start(ol[i]);
                }
            }
            else if (mt == 2)
            {
                //2.thread pool
                PES.Beehive.Logging.Logger.Trace("在线程池,将启动" + page + "个线程来设置Memcached缓存,每个线程处理" + maxSize + "条数据");
                System.Threading.WaitCallback callback = new System.Threading.WaitCallback(SetData);
                for (int i = 0; i < page; i++)
                {
                    System.Threading.ThreadPool.QueueUserWorkItem(callback, ol[i]);
                }
            }
        }