コード例 #1
0
ファイル: Ratings.cs プロジェクト: Dracontis/Ratings
 /// <summary>
 /// Write record for squad i in XML file
 /// </summary>
 /// <param name="id">Squad ID. Defferent with IndexId which starts with zero</param>
 /// <param name="record">String to write into XML element</param>
 public static void WriteRecordBySquadId(int id, String record)
 {
     ParameterizedThreadStart p = new ParameterizedThreadStart(WriteRecordBySquadId);
     Thread writeThread = new Thread(p);
     ThreadParams threadParams = new ThreadParams(id, record, syncObject);
     writeThread.Start(threadParams);
 }
コード例 #2
0
ファイル: ThreadFactory.cs プロジェクト: jdeter14/game1
        /// <summary>
        /// Creates a thread.
        /// </summary>
        /// <param name="name">The name of the thread.</param>
        /// <param name="proc">The procedure to run in the thread.</param>
        /// <returns>
        /// The thread
        /// </returns>
        public Thread CreateThread(string name, ParameterizedThreadStart proc)
        {
            var t = new Thread(proc);
            t.Name = name;

            return t;
        }
コード例 #3
0
 public static Thread ExecAsync(ParameterizedThreadStart start, object state)
 {
     Thread _th = new Thread(start);
     _th.IsBackground = true;
     _th.Start(state);
     return _th;
 }
コード例 #4
0
        public void MultipleThreads()
        {
            GenericListener myListener = new GenericListener();
            ManualResetEvent ev = new ManualResetEvent(false);
            ArrayList threads = new ArrayList();
            System.Diagnostics.Trace.Listeners.Add(myListener);

            for (int i = 0; i < 20; i++)
            {
                ParameterizedThreadStart ts = new ParameterizedThreadStart(MultipleThreadsWorker);
                Thread t = new Thread(ts);
                threads.Add(t);
                t.Start(ev);
            }
            // now let the threads go
            ev.Set();

            // wait for the threads to end
            int x = 0;
            while (x < threads.Count)
            {
                while ((threads[x] as Thread).IsAlive)
                    Thread.Sleep(50);
                x++;
            }
        }
コード例 #5
0
        public PasswordDismisser(string password)
        {
            ParameterizedThreadStart workerStart = new ParameterizedThreadStart(DismissPasswordDialog);
            Thread WorkerThread = new Thread(workerStart);
			WorkerThread.Name = MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name;
			WorkerThread.Start(password);
        }
コード例 #6
0
ファイル: frm_thread.cs プロジェクト: topomondher/web_helper
        private void btn_start_Click(object sender, EventArgs e)
        {
            //线程更新窗体内容
            _thread = new Thread(new ThreadStart(set_txt));
            _thread.Start();

            //线程传递参数
            ParameterizedThreadStart start = new ParameterizedThreadStart(set_txt);
            Thread thread = new Thread(start);
            object obj = "From Thread With Pareameter:Hello ParameterizedThreadStart!!! ";
            thread.Start(obj);

            Thread thread2 = new Thread(() => set_txt("From Thread With Lambda:Hello Lam!!!"));
            thread2.Start();

            ThreadPool.SetMaxThreads(100, 50);
            ThreadPool.QueueUserWorkItem(set_txt, "From Thread With ThreadPool:Hello ThreadPool!!!");

            //传递BsonDocument
            BsonDocument doc_input = new BsonDocument();
            doc_input.Add("sleep", 700);
            doc_input.Add("txt", "From BsonDocument!!!");

            ParameterizedThreadStart start3 = new ParameterizedThreadStart(set_txt_with_doc);
            Thread thread3 = new Thread(start3);
            object obj3 = (object)doc_input;
            thread3.Start(obj3);

            //异步调用
            D_Add handler = new D_Add(f_add);
            sb.AppendLine("Start Add!!");
            IAsyncResult result = handler.BeginInvoke(1, 2, new AsyncCallback(f_complete), "AsycState:OK");
            sb.AppendLine("Start do other work!!");
            this.txt_result.Text = sb.ToString();
        }
コード例 #7
0
        public static void WaysToStartThreads()
        {
            // 1
            // Passing the name of the method name to be executed in the ctor directly without using ThreadStart
            var thread1 = new Thread(DoSomeWork);
            thread1.Start();

            // 2
            // Passing the ThreadStart delegate  which points to a method name to be executed
            var threadStart = new ThreadStart(DoSomeWork);
            var thread2 = new Thread(threadStart);
            thread2.Start();

            // 3
            // Passing the ParametrizedThreadStart delegate  which points to a method to be executed
            var parametrizedThreadStart = new ParameterizedThreadStart(DoSomeWorkWithParameter);
            var thread3 = new Thread(parametrizedThreadStart);
            thread3.Start(2);

            // 4
            // Passing a Lambda expression in the Thread class constructor and subsequently calling the Start method
            var thread4 = new Thread(() =>
            {
                int x = 5;
                for (int i = 0; i < x; i++)
                {
                    Console.WriteLine(i);
                }
            });

            thread4.Start();

            // 5
            // Leveraging ThreadPools, call ThreadPool.QueueUserWorkItem passing in the method name to be executed
            ThreadPool.QueueUserWorkItem(DoSomeWorkWithParameter);
            ThreadPool.QueueUserWorkItem(DoSomeWorkWithParameter, 4);

            // 6
            // Using TPL (Task Parallel Library). Create a Task<T>, where T is the return type of the method to be executed.
            Task<string> task = Task.Factory.StartNew<string>(DoSomeStringWork);
            var result = task.Result;

            // 7
            // Using Asynchronous Delegates
            Func<string, string> work = DoSomeStringWork;
            IAsyncResult res = work.BeginInvoke("Hello", null, null);
            string result1 = work.EndInvoke(res);

            ////TODO: Explicit use of Thread class

            //Threadpool

            //Task Parallel Library

            //Action class with lambda functions

            //BeginInvoke

            //BackgroundWorker
        }
コード例 #8
0
        /// <summary>
        /// 连接客户端
        /// </summary>
        private  void WatchConnecting()
        {
            while (true)//持续不断的监听客户端的请求
            {
                //开始监听 客户端连接请求,注意:Accept方法,会阻断当前的线程
                Socket connection = socketWatch.Accept();
                if (connection.Connected && !dict.ContainsKey(connection.RemoteEndPoint.ToString().Substring(0, connection.RemoteEndPoint.ToString().IndexOf(":"))))
                {
                    //向列表控件中添加一个客户端的Ip和端口,作为发送时客户的唯一标识
                    // listbOnline.Items.Add(connection.RemoteEndPoint.ToString());
                    //将与客户端通信的套接字对象connection添加到键值对集合中,并以客户端Ip做为健

                    //list.Items.Add("IP地址", connection.RemoteEndPoint.ToString());
                    string[] str = new string[]{
                        "客户端在线",
                      connection.RemoteEndPoint.ToString().Substring(0, connection.RemoteEndPoint.ToString().IndexOf(":"))
                    };
                    uishow.ShwMsgforView(list, str);
                    dict.Add( connection.RemoteEndPoint.ToString().Substring(0, connection.RemoteEndPoint.ToString().IndexOf(":")), connection);

                    //创建通信线程
                    ParameterizedThreadStart pts = new ParameterizedThreadStart(RecMsg);
                    Thread thradRecMsg = new Thread(pts);
                    thradRecMsg.IsBackground = true;
                    thradRecMsg.Start(connection);

                }
              
            }
        }
コード例 #9
0
 /// <summary>
 /// creates a new browser instance and displays a given html code
 /// </summary>
 /// <param name="html">the html code to display</param>
 public static void ShowHTML(string html)
 {
     ParameterizedThreadStart threadStart = new ParameterizedThreadStart(CreateBrowserAndShowIt);
     Thread thread = new Thread(threadStart);
     thread.SetApartmentState(ApartmentState.STA);
     thread.Start(html);
 }
コード例 #10
0
ファイル: Capture.cs プロジェクト: kashwaa/Capture
        private void recordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Select s =r== null?new Select():new Select(r);
            recordToolStripMenuItem.Enabled = false;
            if (s.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                recordToolStripMenuItem.Enabled = true;
                return;
            }
            r = s.recData;
            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                r.path = saveFileDialog1.FileName;
            }
            else
            {
                recordToolStripMenuItem.Enabled = true;
                return;
            }
            recordToolStripMenuItem.Enabled = true;

            ParameterizedThreadStart pts = null;
            recorder = RecorderFactory.CreateRecorder(Path.GetExtension(r.path).ToLower());
            pts = new ParameterizedThreadStart(recorder.Record);
            Thread t = new Thread(pts);
            t.Start(r);
            recordToolStripMenuItem.Enabled = false;
            stopToolStripMenuItem.Enabled = true;
            pauseToolStripMenuItem.Enabled = true;
        }
コード例 #11
0
 public static void Run(ParameterizedThreadStart whatToRun, object param)
 {
     InheritedContextThreadRunner runner = new InheritedContextThreadRunner(whatToRun);
     Thread thread = new Thread(new ParameterizedThreadStart(runner.Run));
     thread.IsBackground = true;
     thread.Start(param);
 }
コード例 #12
0
ファイル: frmDisk.cs プロジェクト: WeslieRoco/Roco_Shell
 private void chkdsk_Click(object sender, EventArgs e)
 {
     //docmd("chkdsk.exe", disk + ":");
     ParameterizedThreadStart p = new ParameterizedThreadStart(docmd2);
     IAsyncResult i=p.BeginInvoke(new string[] { "chkdsk", disk + ":" }, null, null);
     //p.EndInvoke(i);
 }
コード例 #13
0
ファイル: ThreadRepository.cs プロジェクト: WilliamPring/SET
 /// <summary>
 /// Adds the specified name.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="threadSt">The thread st.</param>
 /// <param name="mLine">The m line.</param>
 public void Add(string name, ParameterizedThreadStart threadSt, Graphics mLine)
 {
     Thread trd = new Thread(threadSt);
     trd.Name = name;
     threads.Add(trd);
     trd.Start(mLine);
 }
コード例 #14
0
ファイル: SmartThread.cs プロジェクト: liguifa/VMM
 public void Invoke(ParameterizedThreadStart func)
 {
     Thread thread = new Thread(func);
     thread.IsBackground = true;
     thread.Start();
     threadList.Add(thread);
 }
コード例 #15
0
ファイル: Program.cs プロジェクト: Meowse/student1
        static void Main()
        {
            int[] inputValues = new int[2];

            Program p = new Program();
            Calculator c = new Calculator();

            // Get first numeric value.
            inputValues[0] = p.GetNumericValue();

            // Get second numeric value.
            inputValues[1] = p.GetNumericValue();

            // TODO: Create an instance of the ParameterizedThreadStart delegate
            //      passing in the Add method of the Calculator class.
            ParameterizedThreadStart parameterizedThreadStart = new ParameterizedThreadStart(c.Add);

            // TODO: Declare and create an instance of the secondary thread
            //      passing in the delegate instance.
            Thread thread = new Thread(parameterizedThreadStart);
            //Thread thread = new Thread(c.Add);

            //TODO:  Start the secondary thread passing in the object data.
            thread.Start(inputValues);

            System.Threading.Thread.Sleep(2500);

            Console.WriteLine("\nTotal values: {0}",
                c.TotalValue);

            Console.Write("\nPress any key to end.");
            Console.ReadLine();
        }
コード例 #16
0
ファイル: SplashForm.cs プロジェクト: Rychard/MD5Helper
        public void Calculate(String filepath)
        {
            this.Show();

            try
            {
                if (File.Exists(filepath))
                {
                    FileInfo fi = new FileInfo(filepath);
                    FileSize fs = new FileSize(fi.Length);

                    lblStatus.Text = "Calculating MD5... (For large files this may take a while)";
                    lblFilename.Text = filepath;
                    lblFileSize.Text = fs.ToString();

                    ParameterizedThreadStart pt = new ParameterizedThreadStart(GetMD5);
                    Thread t = new Thread(pt);
                    t.Start(filepath);
                }
                else
                {
                    this.Close();
                    MessageBox.Show("File does not exist.");
                    Application.Exit();
                }
            }
            catch (Exception)
            {
                // If an exception is thrown, it's likely that the file is in use.
                MessageBox.Show("File is currently in use by another application.");
                Application.Exit();
            }
        }
コード例 #17
0
ファイル: Form1.cs プロジェクト: arturcp/Word-Occurencies
        private void count_Click(object sender, EventArgs e)
        {
            string text = string.Empty;
            if (rbCopyPaste.Checked)
                text = content.Text;
            else
            {
                openFileDialog1.Filter = "Arquivos do Word (*.doc)|*.doc|Arquivos texto(*.txt)|*.txt|Arquivos rich text(*.rtf)|*.rtf";
                DialogResult result = openFileDialog1.ShowDialog();

                if (result != System.Windows.Forms.DialogResult.OK)
                    return;

                using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
                {
                    text = reader.ReadToEnd();
                }
            }

            ParameterizedThreadStart pts = new ParameterizedThreadStart(StartWordGathering);
            Thread t = new Thread(pts);
            t.Start(text);

            //WordList wordList = GetHash(text);
            //ListByWordCount(wordList);
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: eyecat/Jiggler
 private static void _StartACountingThread(string threadName)
 {
     var parameterizedThreadStart = new ParameterizedThreadStart(_SharedCount);
     var threadOne = new Thread(parameterizedThreadStart);
     threadOne.IsBackground = false;
     threadOne.Start(threadName);
 }
コード例 #19
0
ファイル: MPServer.cs プロジェクト: rockhowse/Gurkenplayer
 //Constructor
 /// <summary>
 /// Private Server constructor used in the singleton pattern. It initialized the config.
 /// </summary>
 public MPServer(MPSharedCondition condition)
 {
     stopProcessMessageThread = condition ?? new MPSharedCondition(false);
     ResetConfig();
     pts = new ParameterizedThreadStart(this.ProcessMessage);
     messageProcessingThread = new Thread(pts);
 }
コード例 #20
0
ファイル: Program.cs プロジェクト: ZLLselfRedeem/zllinmitu
        static void Main(string[] args)
        {
            Console.WriteLine("***** The Amazing Threading App *****\n");
            Console.Write("Do you want [1] or [2] threads?\n");
            string threadChance = Console.ReadLine();
            Thread primaryThread = Thread.CurrentThread;
            primaryThread.Name = "Primary";
            Limitation lm = new Limitation(8, 1400);

            Console.WriteLine("-> {0} is executing Main()", Thread.CurrentThread.Name);
            switch (threadChance)
            {
                case "2":
                    // ThreadStart threadStart = new ThreadStart(TestThreads);
                    ParameterizedThreadStart threadStart = new ParameterizedThreadStart(TestThreads);
                    Thread scdTread = new Thread(threadStart);
                    scdTread.Name = "Secondary";
                    scdTread.Start(lm);
                    break;
                case "1":
                    TestThreads(lm);
                    break;
                default:
                    Console.WriteLine("I don't know you want... you get 1 thread.");
                    goto case "1";
                
            }
            MessageBox.Show("I'm busy!", "Work on main thread...");
            waitHandle.WaitOne();
            Console.WriteLine("Other thread is done!");
            Console.ReadLine();
        }
コード例 #21
0
        /// <summary>
        /// 连接服务器方法,循环创建线程用于连接每台服务器
        /// </summary>
        /// <param name="ObjIp">传入的Ip对象集合</param>
        public void connect(object ObjIp)
        {
            List<ClientInfo> IpAndport = (List<ClientInfo>)ObjIp;

            for (int i = 0; i < IpAndport.Count; i++)
            {
                IsApplyRetry.Add(IpAndport[i].Ip,false);
                ManualResetEvent ConnectTimeout = new ManualResetEvent(false);
                DictTimeoutObject.Add(IpAndport[i].Ip, TimeoutObject);
                ManualResetEvent SendTimeout = new ManualResetEvent(false);
                DictSendoutObject.Add(IpAndport[i].Ip, SendTimeout);
                ManualResetEvent RecTimeout = new ManualResetEvent(false);
                DictRecoutObject.Add(IpAndport[i].Ip, RecTimeout);

                ParameterizedThreadStart pts = new ParameterizedThreadStart(AloneConnect);
                Thread thradRecMsg = new Thread(pts);
                thradRecMsg.IsBackground = true;
                thradRecMsg.Start(IpAndport[i]);
            }
            ParameterizedThreadStart p = new ParameterizedThreadStart(Testonline);
            Thread testonline = new Thread(p);
            testonline.IsBackground = true;
            testonline.Start(IpAndport);

            ParameterizedThreadStart handlemessage = new ParameterizedThreadStart(HandleMessage);
            Thread handle = new Thread(handlemessage);
            handle.IsBackground = true;
            handle.Start();
        }
コード例 #22
0
ファイル: MPClient.cs プロジェクト: rockhowse/Gurkenplayer
 /// <summary>
 /// MPCLient constructor with MPThreadStopCondition as a parameter.
 /// </summary>
 /// <param name="condition">The condition to stop the ProcessMessageThread.</param>
 public MPClient(MPSharedCondition condition)
 {
     StopMessageProcessingThread = condition ?? new MPSharedCondition(false);
     ResetConfig();
     netClient = new NetClient(config);
     pts = new ParameterizedThreadStart(this.ProcessMessage);
 }
コード例 #23
0
ファイル: Login.xaml.cs プロジェクト: Rorymon/cameyo
 private void DoLogin(string login, string password)
 {
     var threadStart = new ParameterizedThreadStart(LoginAsync);
     var thread = new Thread(threadStart);
     PreloaderStart();
     thread.Start(new Credentials() { Login = login, Password = password });
 }
コード例 #24
0
ファイル: PixelLayer.cs プロジェクト: OliveiraThales/GeoCache
        protected override void GetSource( Envelope extent, int width, int height, DynamicLayer.OnImageComplete onComplete )
        {
            _currentWidth = width;
            _currentHeight = height;

            MapPoints = new List<MapPoint>();

            //Make up some dummy data
            int count = 0;
            while( count < 1000 )
            {
                MapPoints.Add( new MapPoint( extent.XMin + ( extent.Width * ( _random.Next( 100 ) / 100.00 ) ),
                    extent.YMin + ( extent.Height * ( _random.Next( 100 ) / 100.00 ) ),
                    extent.SpatialReference ) );
                count++;
            }
            //Make up some dummy data

            _pngRenderer = new PixelPngRenderer( _currentWidth, _currentHeight, MapPoints );

            ParameterizedThreadStart starter = new ParameterizedThreadStart( ( pngRenderer ) =>
            {
                Stream imageStream = InitalizeImage( pngRenderer as PixelPngRenderer );

                Dispatcher.BeginInvoke( () =>
                {
                    _image = new BitmapImage();
                    _image.SetSource( imageStream );
                    onComplete( _image, width, height, extent );
                } );
            } );
            new Thread( starter ).Start( _pngRenderer );
        }
コード例 #25
0
ファイル: ThreadBreak.cs プロジェクト: yellowwood/cyqdata
 /// <summary>
 /// ���ȫ���߳�[ͨ�����߳��Ǹ���ѭ������ʱ��������]
 /// </summary>
 /// <param name="start"></param>
 public static void AddGlobalThread(ParameterizedThreadStart start)
 {
     if (globalThread.Count == 0)//��һ�μ��أ�������п��ܴ��ڵ��߳�Break��
     {
         ClearSchema();
         ClearThreadBreak(string.Empty);
     }
     if (!globalThread.Contains(start))
     {
         lock (lockThreadObj)
         {
             try
             {
                 if (!globalThread.Contains(start))
                 {
                     globalThread.Add(start);
                     Thread thread = new Thread(start);
                     thread.IsBackground = true;
                     thread.Start(thread.ManagedThreadId);
                 }
             }
             catch (Exception err)
             {
                 Log.WriteLogToTxt(err);
             }
         }
     }
 }
コード例 #26
0
ファイル: WaitForm.cs プロジェクト: jogibear9988/ormbattle
 public WaitForm(ParameterizedThreadStart action, object parameter ) : this()
 {
     this.parameter = parameter;
     this.action = action;
     this.thread = new Thread(this.StartWorkerThread);
     this.thread.Start();
 }
コード例 #27
0
    public static IEnumerator Start(ParameterizedThreadStart startMethod, Action completeCallback, float delay)
    {
        if(debugMode) Debug.Log("ThreadManager.Start");

        int id = threadCount++;
        threads.Add(id, new Thread(startMethod));

        yield return new WaitForSeconds(delay);

        if(debugMode) Debug.Log("ThreadManager: Starting Thread '" + startMethod.Method.Name + "'");
        if(threads.ContainsKey(id))
        {
            threads[id].Start(id);
        }

        while(IsRunning(id))
        {
            yield return new WaitForEndOfFrame();
        }

        yield return new WaitForEndOfFrame();
        if(debugMode) Debug.Log("ThreadManager: Ending Thread '" + startMethod.Method.Name + "' with callback '" + completeCallback.Method.Name + "'");

        completeCallback();
    }
コード例 #28
0
ファイル: JobQueue.cs プロジェクト: tyzmodo/chan-archiver
    public JobQueue(string QueueName)
    {
        this._queue = new List<QueueItem>();

            ParameterizedThreadStart pts = new ParameterizedThreadStart(work);
            _worker = new Thread(pts);
            _worker.Start();
    }
コード例 #29
0
ファイル: PcPlatform.cs プロジェクト: mind0n/hive
		public override object CreateThread(J.ThreadWorker worker, object argument = null, bool isBackground = true, bool isStart = true)
		{
			ParameterizedThreadStart ts = new ParameterizedThreadStart(worker);
			Thread th = new Thread(ts);
			th.IsBackground = isBackground;
			th.Start(argument);
			return th;
		}
コード例 #30
0
ファイル: Thread.cs プロジェクト: randomize/VimConfig
 public Thread(ParameterizedThreadStart start)
 {
     if (start == null)
     {
         throw new ArgumentNullException("start");
     }
     this.SetStartHelper(start, 0);
 }
コード例 #31
0
        static void Main(string[] args)
        {
            IImageWriter imageWriter = new PPMImageWriter();
            int          sizeX = 256, sizeY = 256, sampleCount = 16, threadCount = 4;

            float windowScale = 2.0f;

            window = new Window((uint)sizeX, (uint)sizeY, windowScale);

            float ratio = sizeX / sizeY; // 2 for 200x100

            Camera        camera  = new Camera(90.0f, ratio);
            List <Thread> threads = new List <Thread>();

            Dictionary <int, Color> data = new Dictionary <int, Color>();

            RayValueContainer.instance.colors = new List <Dictionary <int, Color> >();
            TextureContainer.instance.LoadTexture("billiardBall.ppm");

            for (int i = 0; i < threadCount; ++i)
            {
                RayValueContainer.instance.colors.Add(new Dictionary <int, Color>());
                totalRaysComplete.Add(0);
            }

            for (int i = 0; i < threadCount; ++i)
            {
                var threadStart = new ParameterizedThreadStart(RayThread);
                threads.Add(new Thread(threadStart));
                threads[i].Start(new RayThreadData(i, threadCount, sizeX, sizeY, sampleCount, camera));
                Console.WriteLine($"Thread {i} started");
            }


            DateTime startTime = DateTime.Now;

            bool threadsDone = false;

            while (!threadsDone)
            {
                threadsDone = true;
                for (int i = 0; i < threadCount; ++i)
                {
                    if (threads[i].IsAlive)
                    {
                        threadsDone = false; break;
                    }
                }
                window.SetScreenData(sizeX, sizeY, RayValueContainer.instance.colors);
                window.Render();
            }


            Console.WriteLine("Merging dictionaries");
            foreach (Dictionary <int, Color> dictionary in RayValueContainer.instance.colors)
            {
                foreach (KeyValuePair <int, Color> kvp in dictionary)
                {
                    if (!data.TryAdd(kvp.Key, kvp.Value))
                    {
                        data[kvp.Key] += kvp.Value;
                    }
                }
            }

            imageWriter.Write(sizeX, sizeY, data.OrderBy(kp => kp.Key).Select(kp => kp.Value).ToArray(), "output");

            DateTime endTime = DateTime.Now;

            Console.WriteLine($"Render took {(endTime - startTime).TotalSeconds}s");
            Console.WriteLine($"Average time per ray: {(endTime - startTime).TotalSeconds / (sizeX * sizeY * sampleCount)}s ({1 / ((endTime - startTime).TotalSeconds / (sizeX * sizeY * sampleCount))} rays/sec)");
            Console.Write("Press any key to exit... ");
            Console.ReadLine();
            window.Close();
        }
コード例 #32
0
 public static RuntimeThread Create(ParameterizedThreadStart start, int maxStackSize) => throw new NotImplementedException();
コード例 #33
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Parallel.Invoke(() => Parallel_Invoke_1.Task1(), () => Parallel_Invoke_1.Task2());

            //Parallel ForEach
            Paralle_ForEaach paralle_ForEaach = new Paralle_ForEaach();

            paralle_ForEaach.WorkOnItem("Normal");
            List <int> myList = new List <int>();

            for (int i = 0; i < 5; i++)
            {
                myList.Add(i);
            }
            var items = Enumerable.Range(5, 10);

            /*
             * The Parallel.ForEach method accepts two parameters. The first parameter is an
             * IEnumerable
             * collection (in this case the list myList). The second parameter provides the action to be performed on each item in the list. You can see some of the output from this program
             * below. Note that the tasks are not completed in the same order that they were started.
             */
            Parallel.ForEach(myList, item => { paralle_ForEaach.WorkOnItem(item); });
            Console.WriteLine("Tetsing from enumarable");
            // Parallel.ForEach(items, item => { paralle_ForEaach.WorkOnItem(item); });

            /*
             * The Parallel.For method can be used to parallelize the execution of a for loop, which is governed
             * by a control variable.
             *
             *  This implements a counter starting at 0 (the first parameter of the Parallel.For method),
             * for the length of the items array (the second parameter of the Parallel.For method). The third
             * parameter of the method is a lambda expression, which is passed a variable that provides the
             * counter value for each iteration.
             */

            var items3 = Enumerable.Range(100, 5).ToArray();
            //   Parallel.For(1, items3.Length, i => { paralle_ForEaach.WorkOnItem(items3[i]); });

            Create_Task1 myTask   = new Create_Task1();
            Task         newTask1 = new Task(() => myTask.DoWork());

            newTask1.Start();
            newTask1.Wait();

            /*
             *
             * The Task.Run method uses the TaskFactory.StartNew method to create and start the task,
             * using the default task scheduler that uses the .NET framework thread pool. The Task class
             * exposes a Factory property that refers to the default task scheduler.
             * You can create your own task scheduler or run a task scheduler in the synchronization
             * context of another processor. You can also create your own TaskFactory if you want to create a
             * number of tasks with the same configuration. The Run method, however, is the preferred way to
             * create a simple task, particularly if you want to use the task with async and await (covered later
             * in this chapter).*/
            Task <int> newTask2 = Task.Run(() => { return(myTask.Work()); });

            Console.WriteLine(newTask2.Result);
            Creating_Threads ct = new Creating_Threads();

            Thread myThread = new Thread(ct.HellThread);

            myThread.Start();

            /* passing data to athread */
            ParameterizedThreadStart parameterizedThreadStart = new ParameterizedThreadStart(ct.DoWork);
            Thread thread = new Thread(parameterizedThreadStart);

            thread.Start(89);

            //same as with lamda expression
            Thread t = new Thread(my =>
            {
                ct.DoWork(my);
            });

            t.Start(2000);

            for (int i = 300; i < 306; i++)
            {
                int state = i;
                ThreadPool.QueueUserWorkItem((s) => ct.DoWork(state));
            }

            /* Canceling a task */
            CancellationTokenSource myCTS = new CancellationTokenSource();
            Cancel_task             myCT  = new Cancel_task();
            Task clock = Task.Run(() => myCT.Clock(myCTS.Token));

            Console.WriteLine("press any key to end");
            Console.ReadKey();
            if (clock.IsCompleted)
            {
                Console.WriteLine("clock completed");
            }
            else
            {
                try
                {
                    myCTS.Cancel();
                    clock.Wait();
                }
                catch (AggregateException ex)
                {
                    Console.WriteLine($"clock stopped nhaikaaaa : {ex.InnerExceptions[0].ToString()}");
                }
            }
        }
コード例 #34
0
ファイル: TextureScale.cs プロジェクト: defacto2k15/PwMgr
        private static void ThreadedScale(Texture2D tex, int newWidth, int newHeight, bool useBilinear)
        {
            texColors = tex.GetPixels();
            newColors = new Color[newWidth * newHeight];
            if (useBilinear)
            {
                ratioX = 1.0f / ((float)newWidth / (tex.width - 1));
                ratioY = 1.0f / ((float)newHeight / (tex.height - 1));
            }
            else
            {
                ratioX = ((float)tex.width) / newWidth;
                ratioY = ((float)tex.height) / newHeight;
            }
            w  = tex.width;
            w2 = newWidth;
            var cores = Mathf.Min(SystemInfo.processorCount, newHeight);
            var slice = newHeight / cores;

            finishCount = 0;
            if (mutex == null)
            {
                mutex = new Mutex(false);
            }
            if (cores > 1)
            {
                int        i = 0;
                ThreadData threadData;
                for (i = 0; i < cores - 1; i++)
                {
                    threadData = new ThreadData(slice * i, slice * (i + 1));
                    ParameterizedThreadStart ts = useBilinear
                        ? new ParameterizedThreadStart(BilinearScale)
                        : new ParameterizedThreadStart(PointScale);
                    Thread thread = new Thread(ts);
                    thread.Start(threadData);
                }
                threadData = new ThreadData(slice * i, newHeight);
                if (useBilinear)
                {
                    BilinearScale(threadData);
                }
                else
                {
                    PointScale(threadData);
                }
                while (finishCount < cores)
                {
                    Thread.Sleep(1);
                }
            }
            else
            {
                ThreadData threadData = new ThreadData(0, newHeight);
                if (useBilinear)
                {
                    BilinearScale(threadData);
                }
                else
                {
                    PointScale(threadData);
                }
            }

            tex.Resize(newWidth, newHeight);
            tex.SetPixels(newColors);
            tex.Apply();

            texColors = null;
            newColors = null;
        }
コード例 #35
0
ファイル: MainWindow.xaml.cs プロジェクト: xyqgcs/IPSearch40
 /// <summary>
 ///
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void DeviceSearcher_NetworkDeviceSearched(object sender, NetworkDeviceSearchedEventArgs e)
 {
     try
     {
         ParameterizedThreadStart parameterizedThreadStart = x =>
         {
             lock (this)
             {
                 NetworkDeviceInformation deviceModel = x as NetworkDeviceInformation;
                 if (this.DeviceSearcher.ProtocolType.Contains(deviceModel.ProtocolType) == false)
                 {
                     return;
                 }
                 if (deviceModel != null)
                 {
                     if (this.Devices.Where(y => y.PhysicalAddress == deviceModel.NetworkInterface?.PhyscialAddress?.ToUpper()).SingleOrDefault() == null)
                     {
                         String     howellModel      = null;
                         DeviceType howellDeviceType = Helper.GetDeviceType(deviceModel.Model, (FactoryType == "Howell8000") ? false : true, Helper.AllDevices, deviceModel.Classification, out howellModel);
                         if (Helper.AllDevices == false && howellDeviceType == DeviceType.None)
                         {
                             return;
                         }
                         DeviceModel device = new DeviceModel()
                         {
                             DHCP                     = (deviceModel.NetworkInterface?.AddressingType == Howell.Industry.NetworkAddressingType.Dynamic) ? true : false,
                             Dns1                     = deviceModel.NetworkInterface?.IPAddress?.IPv4Address?.PrimaryDNS,
                             Dns2                     = deviceModel.NetworkInterface?.IPAddress?.IPv4Address?.SecondaryDNS,
                             Gateway                  = deviceModel.NetworkInterface?.IPAddress?.IPv4Address?.DefaultGateway,
                             IPAddress                = deviceModel.NetworkInterface?.IPAddress?.IPv4Address?.Address,
                             SubnetMask               = deviceModel.NetworkInterface?.IPAddress?.IPv4Address?.Subnetmask,
                             Hardware                 = deviceModel.Firmware,
                             Software                 = deviceModel.Software,
                             IsSelected               = false,
                             Model                    = howellModel,
                             Name                     = deviceModel.Name,
                             No                       = (++this.No).ToString("0000"),
                             Username                 = "******",
                             Password                 = (FactoryType == "Howell8000") ? "howell1409" : "12345",
                             PhysicalAddress          = deviceModel.NetworkInterface.PhyscialAddress.ToUpper(),
                             Port                     = deviceModel.Uri.Port,
                             SerialNumber             = deviceModel.SerialNumber,
                             VideoChannelCount        = deviceModel.VideoCaptureInputChannelCount ?? 0 + deviceModel.VideoNetworkInputChannelCount ?? 0,
                             DeviceType               = howellDeviceType,
                             NetworkDeviceInformation = deviceModel,
                             ProtocolType             = deviceModel.ProtocolType
                         };
                         //如果是摄像机,读取OSD名称
                         if (device.DeviceType == DeviceType.IPCamera ||
                             device.DeviceType == DeviceType.FaceCamera ||
                             device.DeviceType == DeviceType.IntelligentCamera ||
                             device.DeviceType == DeviceType.VehicleCamera)
                         {
                             System.Threading.ThreadPool.QueueUserWorkItem(ReadOSDName, device);
                         }
                         this.Devices.Add(device);
                         CheckIPConflict(device.IPAddress);
                     }
                 }
             }
         };
         Application.Current.Dispatcher.BeginInvoke(parameterizedThreadStart, e.DeviceInfo);
     }
     catch (Exception ex)
     {
         Helper.Logger.Error(String.Format("DeviceSearcher_NetworkDeviceSearched {0} error.", this.DeviceCatalog), ex);
     }
 }
コード例 #36
0
 //protected abstract IThread Thread_NewThread(ParameterizedThreadStart start);
 protected override IPCLThread Thread_NewThread(ParameterizedThreadStart start)
 {
     return(new PCLThread(new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(start))));
 }
コード例 #37
0
 public static RuntimeThread Create(ParameterizedThreadStart start) => new RuntimeThread(start, 0);
コード例 #38
0
        public ApplicationSprite()
        {
            //__Thread.InternalWorkerInvoke_4ebbe596_06000030(this);
            //this.__out_Method_6d788eff_06000003();

            // "X:\jsc.svn\examples\actionscript\async\AsyncWorkerTask\AsyncWorkerTask.sln"
            // X:\jsc.svn\examples\actionscript\async\AsyncWorkerTask\AsyncWorkerTask\ApplicationSprite.cs
            // X:\jsc.svn\examples\actionscript\FlashWorkerExperiment\FlashWorkerExperiment\ApplicationSprite.cs


            // https://forums.adobe.com/thread/1164500

            // this looks like chrome context capture
            #region worker
            if (!Worker.current.isPrimordial)
            {
                var sw = Stopwatch.StartNew();

                // iOS workers is still on the roadmap.  I don't have a release date, but I know it'll be an extended beta type of feature.
                // Most of the concurrency work was gated on the new AOT compiler work, which is still being actively worked on.
                // Lots of bug and performance fixes were added to AIR 15 and we're not stopping there.

                var xfromWorker = (MessageChannel)Worker.current.getSharedProperty("fromWorker");

                var FunctionToken_TypeFullName = (string)Worker.current.getSharedProperty("FunctionToken_TypeFullName");
                var FunctionToken_MethodName   = (string)Worker.current.getSharedProperty("FunctionToken_MethodName");
                var arg0 = (string)Worker.current.getSharedProperty("arg0");

                //               enter click
                //{ { data = message from worker { { FunctionToken_TypeFullName = TestThreadStart.TheOtherClass, FunctionToken_MethodName = Invoke_6d788eff_0600001c } }, ElapsedMilliseconds = 1713 } }


                IntPtr pp = __IntPtr.OfFunctionToken(null,
                                                     FunctionToken_TypeFullName,
                                                     FunctionToken_MethodName
                                                     );


                MethodInfo mm = new __MethodInfo {
                    _Method = pp
                };

                //    t.text = "after invoke " + new { TheOtherClass.SharedField, sw.ElapsedMilliseconds };

                //xfromWorker.send("message from worker " + new { FunctionToken_TypeFullName, FunctionToken_MethodName });

                //throw null;



                mm.Invoke(null, new object[] { arg0 });

                //               enter click
                //{ { ElapsedMilliseconds = 3103, data = message from worker { { ElapsedMilliseconds = 3057, SharedField = { { data = null, i = 65534, j = 3 } } } } } }
                // {{ ElapsedMilliseconds = 3399, data = message from worker {{ ElapsedMilliseconds = 3352, SharedField = {{ data = hello world, i = 65534, j = 3 }} }} }}

                xfromWorker.send("message from worker " + new { sw.ElapsedMilliseconds, TheOtherClass.SharedField });

                return;
            }
            #endregion

            // {{ os = Windows 7, version = WIN 15,0,0,189, length = 333983, Target = null, Method = { _Target = , _Method = IntPtr { StringToken = , FunctionToken = function Function() {}, ClassToken =  } } }}
            // start0 = new __ParameterizedThreadStart(null, __IntPtr.op_Explicit_4ebbe596_06001686(TheOtherClass.Invoke_6d788eff_0600000c));
            //      start0 = new __ParameterizedThreadStart(null, __IntPtr.OfFunctionToken_4ebbe596_06001687(TheOtherClass.Invoke_6d788eff_0600000c,"TestThreadStart.TheOtherClass","Invoke_6d788eff_0600000c"));
            ParameterizedThreadStart y = TheOtherClass.Invoke;

            // can we call the method
            //            0007 0200034c ScriptCoreLib::ScriptCoreLib.ActionScript.Extensions.ZipFileEntry + Cookie`1

            //Unhandled Exception: System.AggregateException: One or more errors occurred. --->System.InvalidOperationException: internal compiler error at method
            // assembly: X:\jsc.svn\examples\actionscript\Test\TestThreadStart\TestThreadStart\bin\Debug\ScriptCoreLib.dll at
            // type: ScriptCoreLib.ActionScript.BCLImplementation.System.__Single, ScriptCoreLib, Version=4.5.0.0, Culture=neutral, PublicKeyToken=null
            // method: CompareTo
            // Object reference not set to an instance of an object.
            //    at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
            //   at System.Collections.Generic.Dictionary`2.set_Item(TKey key, TValue value)
            //   at jsc.Script.CompilerBase.  .    (Type , MethodBase , LocalVariableInfo , CompilerBase )
            //   at jsc.Script.CompilerBase.<WriteVariableName>b__0(Type , MethodBase , LocalVariableInfo )

            //           Unhandled Exception: System.AggregateException: One or more errors occurred. --->System.InvalidOperationException: internal compiler error at method
            //assembly: X:\jsc.svn\examples\actionscript\Test\TestThreadStart\TestThreadStart\bin\Debug\ScriptCoreLib.dll at
            //type: ScriptCoreLib.ActionScript.BCLImplementation.System.__BitConverter, ScriptCoreLib, Version=4.5.0.0, Culture=neutral, PublicKeyToken=null
            //method: GetBytes
            //Object reference not set to an instance of an object.
            //   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
            //  at System.Collections.Generic.Dictionary`2.set_Item(TKey key, TValue value)
            //  at jsc.Script.CompilerBase.  .    (Type , MethodBase , LocalVariableInfo , CompilerBase )


            //{{ os = Windows 7, version = WIN 15,0,0,189, length = 334356, Target = null, Method = { _Target = , _Method = IntPtr { StringToken = , FunctionToken = function Function() {}, ClassToken =  } }, z = Type { TypeDescription =
            // <type name="TestThreadStart::TheOtherClass" base="Class" isDynamic="true" isFinal="true" isStatic="true">
            //  <extendsClass type="Class"/>
            //  <extendsClass type="Object"/>
            //  <accessor name="prototype" access="readonly" type="*" declaredBy="Class"/>
            //  <method name="Invoke_6d788eff_0600000c" declaredBy="TestThreadStart::TheOtherClass" returnType="void">
            //    <parameter index="1" type="Object" optional="false"/>
            //  </method>
            //  <factory type="TestThreadStart::TheOtherClass">
            //    <extendsClass type="Object"/>
            //  </factory>
            //</type> } }}

            //          {{ os = Windows 7, version = WIN 15,0,0,189, length = 334570, Target = null, Method = { _Target = , _Method = IntPtr { StringToken = ,
            //FunctionToken = function Function() {}, ClassToken =  } }, FullName = TestThreadStart::TheOtherClass, z = Type { TypeDescription = <type name="TestThreadStart::TheOtherClass" base="Class" isDynamic="true" isFinal="true" isStatic="true">
            //  <extendsClass type="Class"/>
            //  <extendsClass type="Object"/>
            //  <accessor name="prototype" access="readonly" type="*" declaredBy="Class"/>
            //  <method name="Invoke_6d788eff_0600000c" declaredBy="TestThreadStart::TheOtherClass" returnType="void">
            //    <parameter index="1" type="Object" optional="false"/>
            //  </method>
            //  <factory type="TestThreadStart::TheOtherClass">
            //    <extendsClass type="Object"/>
            //  </factory>
            //</type> }, zz = Type { TypeDescription = <type name="TestThreadStart::TheOtherClass" base="Class" isDynamic="true" isFinal="true" isStatic="true">
            //  <extendsClass type="Class"/>
            //  <extendsClass type="Object"/>
            //  <accessor name="prototype" access="readonly" type="*" declaredBy="Class"/>
            //  <method name="Invoke_6d788eff_0600000c" declaredBy="TestThreadStart::TheOtherClass" returnType="void">
            //    <parameter index="1" type="Object" optional="false"/>
            //  </method>
            //  <factory type="TestThreadStart::TheOtherClass">
            //    <extendsClass type="Object"/>
            //  </factory>
            //</type> } }}

            //var z = typeof(TheOtherClass);
            //var zz = Type.GetType("TestThreadStart::TheOtherClass");
            //var zz = Type.GetType("TestThreadStart.TheOtherClass");

            //var zMethod = z.GetMethods();

            __MethodInfo p = y.Method;

            //{ { os = Windows 7, version = WIN 15,0,0,189, length = 335268,
            // FunctionToken_TypeFullName = TestThreadStart.TheOtherClass,
            // FunctionToken_MethodName = Invoke_6d788eff_0600000c
            // } }

            //var pt = Type.GetType(p._Method.FunctionToken_TypeFullName);



            //new ParameterizedThreadStart(null, pp);

            //new Delegate();



            var t = new TextField
            {
                multiline = true,
                //wordWrap = true,

                // {{ InternalPrimordialSprite = null, os = Windows 7, version = WIN 15,0,0,189, length = 353988, FunctionToken_TypeFullName = TestThreadStart.TheOtherClass, FunctionToken_MethodName = Invoke_6d788eff_06000016 }}

                text = new
                {
                    // did the compiler set it yet?
                    __Thread.InternalPrimordialSprite,

                    // http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/Capabilities.html
                    Capabilities.os,
                    Capabilities.version,

                    //WorkerDomain = WorkerDomain.isSupported,
                    //Worker = Worker.isSupported,
                    //Worker.current.isPrimordial,

                    this.loaderInfo.bytes.length,

                    // {{ os = Windows 7, version = WIN 15,0,0,189, length = 333411, Target = null, Method = { InternalFunctionPointer = function Function() {} } }}

                    //y.Target,

                    // first step is to call a static method on the other side of thread
                    //y.Method,
                    //y.Method,
                    //y.Method.DeclaringType


                    //z.FullName,

                    //z,

                    p._Method.FunctionToken_TypeFullName,
                    p._Method.FunctionToken_MethodName,
                }.ToString(),

                autoSize = TextFieldAutoSize.LEFT
            };

            t.AttachTo(this);

            t.click += delegate
            {
                var sw = Stopwatch.StartNew();

                t.text = "enter click";

                var w = WorkerDomain.current.createWorker(
                    this.loaderInfo.bytes
                    );

                //p._Method.FunctionToken_TypeFullName,
                //p._Method.FunctionToken_MethodName

                w.setSharedProperty("FunctionToken_TypeFullName", p._Method.FunctionToken_TypeFullName);
                w.setSharedProperty("FunctionToken_MethodName", p._Method.FunctionToken_MethodName);
                w.setSharedProperty("arg0", "hello world");

                var fromWorker = w.createMessageChannel(Worker.current);
                w.setSharedProperty("fromWorker", fromWorker);

                fromWorker.channelMessage +=
                    e =>
                {
                    var data = (string)fromWorker.receive();

                    t.appendText(

                        "\n " + new { sw.ElapsedMilliseconds, data }.ToString()

                        );
                };

                t.text = "enter click";
                w.start();


                //try
                //{
                //    // catch {{ err = ArgumentError: Error #1063: Argument count mismatch on TestThreadStart::TheOtherClass$/Invoke_6d788eff_06000013(). Expected 1, got 0. }}

                //    mm.Invoke(null, new object[1]);
                //    t.text = "after invoke " + new { TheOtherClass.SharedField, sw.ElapsedMilliseconds };
                //}
                //catch (Exception err)
                //{
                //    t.text = "catch " + new { err };
                //}
            };
        }
コード例 #39
0
        public void SessionLocking()
        {
            // Copy updated configuration file for web server process
            Configuration            config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ConnectionStringSettings css    = config.ConnectionStrings.ConnectionStrings["LocalMySqlServer"];
            string curDir           = Directory.GetCurrentDirectory();
            string webconfigPath    = string.Format(@"{0}\SessionLocking\{1}", Directory.GetCurrentDirectory(), @"web.config");
            string webconfigPathSrc = string.Format(@"{0}\SessionLocking\{1}", Directory.GetCurrentDirectory(), @"web_config_src.txt");

            string text = File.ReadAllText(webconfigPathSrc);

            text = text.Replace("connection_string_here", css.ConnectionString);
            Version ver = System.Environment.Version;

            if (ver.Major != 4)
            {
                text = text.Replace("<compilation targetFramework=\"4.0\" />", "");
            }

            File.WriteAllText(webconfigPath, text);

            int port = 12224;

            string webserverPath;

            if (ver.Major == 4)
            {
                webserverPath = @"C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\WebDev.WebServer40.exe";
            }
            else
            {
                webserverPath = @"C:\Program Files (x86)\Common Files\microsoft shared\DevServer\9.0\WebDev.WebServer.exe";
            }
            string webserverArgs = string.Format(" /port:{0} /path:{1}\\SessionLocking", port,
                                                 Path.GetFullPath(@"."));

            DirectoryInfo di = new DirectoryInfo(Path.GetFullPath(curDir));

            Directory.CreateDirectory(Path.GetFullPath(@".\SessionLocking\bin"));
            foreach (FileInfo fi in di.GetFiles("*.dll"))
            {
                File.Copy(fi.FullName, Path.Combine(Path.GetFullPath(@".\SessionLocking\bin\"), fi.Name), true);
            }

            Process webserver = Process.Start(webserverPath, webserverArgs);

            System.Threading.Thread.Sleep(2000);

            // This dummy request is just to get the ASP.NET sessionid to reuse.
            HttpWebRequest      req     = (HttpWebRequest)WebRequest.Create("http://*****:*****@"{0}{1}", url, data.pageName));
                        req1.Timeout = 2000000;
                        WebResponse res1 = req1.GetResponse();
                        Debug.WriteLine(string.Format("Response from {0}", data.pageName));
                        Stream s = res1.GetResponseStream();
                        while (s.ReadByte() != -1)
                        {
                            ;
                        }
                        res1.Close();
                        if (data.FirstDateToUpdate)
                        {
                            firstDt = DateTime.Now;
                        }
                        else
                        {
                            secondDt = DateTime.Now;
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(string.Format("Server error: {0}", e.ToString()));
                        throw;
                    }
                    finally
                    {
                        data.signal.Set();
                    }
                };

                Thread t  = new Thread(ts);
                Thread t2 = new Thread(ts);
                t.Start(new ThreadRequestData()
                {
                    pageName          = "write.aspx",
                    FirstDateToUpdate = true,
                    signal            = re[0]
                });
                t2.Start(new ThreadRequestData()
                {
                    pageName          = "read.aspx",
                    FirstDateToUpdate = false,
                    signal            = re[1]
                });
                WaitHandle.WaitAll(re);
                re[0].Reset();
                Thread t3 = new Thread(ts);
                t3.Start(new ThreadRequestData()
                {
                    pageName          = "write2.aspx",
                    FirstDateToUpdate = false,
                    signal            = re[0]
                });
                WaitHandle.WaitAll(re);
                double totalMillisecs = Math.Abs((secondDt.Value - firstDt.Value).TotalMilliseconds);
                // OK if wait is less than session timeout
                Debug.WriteLine(string.Empty);
                Debug.WriteLine(totalMillisecs);
                Assert.True(totalMillisecs < 30000);
            }
            finally
            {
                webserver.Kill();
            }
        }
コード例 #40
0
 public Thread(ParameterizedThreadStart start, int maxStackSize)
     : this(start)
 {
     GC.KeepAlive(maxStackSize);
 }
コード例 #41
0
        /// <summary>
        /// Filters an GrayImage with a 1D symmetric filter along the X-axis.
        /// (This operation is multithreaded)
        /// </summary>
        /// <param name="data">GrayImage to be operated on</param>
        /// <param name="filter">Filter to use (center tap plus right-hand-side)</param>
        /// <param name="transpose">Transpose the result?</param>
        /// <returns>Transposed, filtered GrayImage.</returns>
        public GrayImage Filter1DSymmetric(GrayImage data, float[] filter, bool transpose)
        {
            GrayImage result = transpose ?
                               new GrayImage(data.Height, data.Width) :
                               new GrayImage(data.Width, data.Height);

#if SILVERLIGHT || WIN
            int startY = 0;

            int destPtr = transpose ?  startY : (startY * result.Width);

            FilterJob job
                = new FilterJob
                {
                filter  = filter,
                data    = data,
                destPtr = destPtr,
                result  = result,
                start   = startY,
                end     = data.Height / 2
                };

            ParameterizedThreadStart del = transpose ?
                                           new ParameterizedThreadStart(FilterPartSymmetricT) :
                                           new ParameterizedThreadStart(FilterPartSymmetric);

            Thread worker = new Thread(del);
            worker.Start(job);

            startY  = data.Height / 2;
            destPtr = transpose ?  startY : (startY * result.Width);


            job.start   = startY;
            job.destPtr = destPtr;
            job.end     = data.Height;

            del((object)job); // Run the appropriate filter in this thread, too

            worker.Join();
#else
            FilterJob job
                = new FilterJob
                {
                filter  = filter,
                data    = data,
                destPtr = 0,
                result  = result,
                start   = 0,
                end     = data.Height
                };

            if (transpose)
            {
                FilterPartSymmetricT(job);
            }
            else
            {
                FilterPartSymmetric(job);
            }
#endif

            return(result);
        }
コード例 #42
0
ファイル: Server.cs プロジェクト: js-numberone/ass2
        static void Main(string[] args)
        {
            TcpListener server = null;

            try
            {
                // Set the TcpListener on port 13000.
                Int32     port      = 13000;
                IPAddress localAddr = IPAddress.Parse("10.192.49.5");

                // TcpListener server = new TcpListener(port);
                server = new TcpListener(localAddr, port);

                // Start listening for client requests.
                server.Start();


                // Enter the listening loop.
                while (true)
                {
                    Console.Write("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine("Connected!");

                    StreamReader sR = new StreamReader(client.GetStream());

                    // Read the username (waiting for the client to use WriteLine())
                    String connectedUsername = sR.ReadLine();
                    connectedUsers.Add(connectedUsername);
                    NetworkStream stream = client.GetStream();


                    Console.WriteLine(connectedUsername + " is connected");


                    StreamWriter sW = new StreamWriter(client.GetStream());

                    //Check for existing clients
                    if (clientStreams.Count == 0)
                    {
                        sW.WriteLine(connectedUsers[0]);
                        // Send the username
                        sW.AutoFlush = true;
                        clientStreams.Add(connectedUsername, stream);
                    }
                    //Send username to all clients
                    else
                    {
                        clientStreams.Add(connectedUsername, stream);
                        int i = 0;
                        foreach (KeyValuePair <string, NetworkStream> user in clientStreams)
                        {
                            sW.WriteLine(connectedUsers[i]);
                            i++;
                            // Send the username
                        }
                    }
                    sW.AutoFlush = true;



                    ParameterizedThreadStart ts = new ParameterizedThreadStart(Worker);
                    Thread clientThread         = new Thread(ts);
                    clientThread.Start(client);
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                // Stop listening for new clients.
                server.Stop();
            }


            Console.WriteLine("\nHit enter to continue...");
            Console.Read();
        }
コード例 #43
0
 public void QueueIdle(ParameterizedThreadStart method, object parameter)
 {
     IdleThreadQueue.Instance.Enqueue(method, parameter);
 }
コード例 #44
0
        private void RecFile(object fileParam)
        {
            File_Info fi = (File_Info)fileParam;

            //开始监听文件传送端口
            Socket     socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep    = new IPEndPoint(((IPEndPoint)socketConn.LocalEndPoint).Address, 8089);

            socket.Bind(iep);
            socket.Listen(1);

            try
            {
                socketRecFile = socket.Accept();
                socket.Close();
            }
            catch
            {
                WriteLog("传输端口无响应");
                snackbar.MessageQueue.Enqueue("传输端口无响应");
            }
            this.Dispatcher.Invoke(new Action(() =>
            {
                WriteLog("开始接收 " + new FileInfo(fi.FileName).Name);
                snackbar.MessageQueue.Enqueue("开始接收 " + new FileInfo(fi.FileName).Name);
            }));

            //开一个线程进行解密
            ParameterizedThreadStart pts = new ParameterizedThreadStart(DecryptData);
            Thread trd = new Thread(pts);

            trd.IsBackground = true;
            trd.Start(fi);

            this.Dispatcher.Invoke(new Action(() =>
            {
                progressBar_recFile.Minimum = 0;
                progressBar_recFile.Maximum = fi.FileLength;
            }));

            //填充后的长度
            long file_length = fi.FileLength + ((fi.FileLength % 16 == 0) ? 0 : (16 - fi.FileLength % 16));
            long offset      = 0;

            while (true)
            {
                int    length = -1;
                byte[] buffer = new byte[File_Buffer_Size];
                try
                {
                    length = socketRecFile.Receive(buffer);
                }
                catch (Exception ex)
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        WriteLog(ex.ToString());
                        WriteLog("传输连接已断开");

                        snackbar.MessageQueue.Enqueue("传输连接已断开,停止接收 " + new FileInfo(fi.FileName).Name);
                    }));
                    break;
                }
                _rwlock.EnterWriteLock();
                FileWrite(fi.FileName + ".tmp", offset, length, buffer);
                _rwlock.ExitWriteLock();
                offset += length;

                this.Dispatcher.Invoke(new Action(() =>
                {
                    progressBar_recFile.Value = offset;
                }));


                if (offset >= file_length)
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        WriteLog(new FileInfo(fi.FileName).Name + " 接收完毕");
                        snackbar.MessageQueue.Enqueue(new FileInfo(fi.FileName).Name + " 接收完毕");

                        progressBar_recFile.IsIndeterminate = true;
                        try
                        {
                            socketRecFile.Close();
                        }
                        catch (Exception ex)
                        {
                            WriteLog(ex.ToString());
                        }
                        socketRecFile = null;
                    }));
                    break;
                }

                System.GC.Collect();
            }

            System.GC.Collect();
        }
コード例 #45
0
        public static void WaysToStartThreads()
        {
            // 1
            // Passing the name of the method name to be executed in the ctor directly without using ThreadStart
            var thread1 = new Thread(DoSomeWork);

            thread1.Start();

            // 2
            // Passing the ThreadStart delegate  which points to a method name to be executed
            var threadStart = new ThreadStart(DoSomeWork);
            var thread2     = new Thread(threadStart);

            thread2.Start();

            // 3
            // Passing the ParametrizedThreadStart delegate  which points to a method to be executed
            var parametrizedThreadStart = new ParameterizedThreadStart(DoSomeWorkWithParameter);
            var thread3 = new Thread(parametrizedThreadStart);

            thread3.Start(2);

            // 4
            // Passing a Lambda expression in the Thread class constructor and subsequently calling the Start method
            var thread4 = new Thread(() =>
            {
                int x = 5;
                for (int i = 0; i < x; i++)
                {
                    Console.WriteLine(i);
                }
            });

            thread4.Start();

            // 5
            // Leveraging ThreadPools, call ThreadPool.QueueUserWorkItem passing in the method name to be executed
            ThreadPool.QueueUserWorkItem(DoSomeWorkWithParameter);
            ThreadPool.QueueUserWorkItem(DoSomeWorkWithParameter, 4);

            // 6
            // Using TPL (Task Parallel Library). Create a Task<T>, where T is the return type of the method to be executed.
            Task <string> task   = Task.Factory.StartNew <string>(DoSomeStringWork);
            var           result = task.Result;

            // 7
            // Using Asynchronous Delegates
            Func <string, string> work = DoSomeStringWork;
            IAsyncResult          res  = work.BeginInvoke("Hello", null, null);
            string result1             = work.EndInvoke(res);

            ////TODO: Explicit use of Thread class

//Threadpool

//Task Parallel Library

//Action class with lambda functions

//BeginInvoke

//BackgroundWorker
        }
コード例 #46
0
 /// <summary>
 /// Creates a new WaitDialog with the specified ThreadStart.
 /// </summary>
 /// <param name="nProgressBarCount">The number of progress bars to include.</param>
 /// <param name="zThreadStart">The ThreadStart to initialize</param>
 /// <param name="zParamObject">The object to pass to the thread method</param>
 /// <param name="sTitle">The title of the wait dialog</param>
 /// <param name="arrayDescriptions">Optional array of strings for each progress bar. (null is allowed)</param>
 /// <param name="nWidth">Desired width of the WaitDialog, must be >100</param>
 public WaitDialog(int nProgressBarCount, ParameterizedThreadStart zThreadStart, object zParamObject, string sTitle, string[] arrayDescriptions, int nWidth)
 {
     m_zParamThreadStart = zThreadStart;
     m_zParamObject      = zParamObject;
     Initialize(nProgressBarCount, sTitle, arrayDescriptions, nWidth);
 }
コード例 #47
0
 public static RuntimeThread Create(ParameterizedThreadStart start, int maxStackSize) => new RuntimeThread(start, maxStackSize);
コード例 #48
0
ファイル: Thread.cs プロジェクト: yangruihan/mono
 void Create(ParameterizedThreadStart start) => SetStartHelper((Delegate)start, 0);
コード例 #49
0
 public SafeSingleThreadSession(ParameterizedThreadStart targetMethod)
 {
     this.paramTargetMethod = targetMethod;
 }
コード例 #50
0
ファイル: Thread.cs プロジェクト: yangruihan/mono
 void Create(ParameterizedThreadStart start, int maxStackSize) => SetStartHelper((Delegate)start, maxStackSize);
コード例 #51
0
    public MyClass()
    {
        starter = SelectJob;

        Del selectDelegate = SelectJob;
    }
コード例 #52
0
        /// <summary> Инициализация потоков сообщений, управляет входящими и исходящими сообщениями. </summary>
        public void InitThreadsMessages()
        {
            if (this.BaseMManager)
            {
                Thread ThreadSendMsg = null;
                //Основной цикл приема сообщений
                ParameterizedThreadStart actionSendMessage = (object classMM) =>
                {
                    MManager mm = (MManager)classMM;
                    while (MManager.LoopProcessing)
                    {
                        //Отправка
                        mm.ProcessSendMessage();
                        Thread.Sleep(1);
                    }
                    mm.qSocket.CloseSocket();
                };
                ThreadSendMsg          = new Thread(actionSendMessage);
                ThreadSendMsg.Priority = ThreadPriority.Highest;
                ThreadSendMsg.Start(this);
            }

            Thread MainThreadProcMsg = null;
            //Основной цикл приема сообщений
            ParameterizedThreadStart actionMessage = (object classMM) =>
            {
                MManager mm = (MManager)classMM;
                while (MManager.LoopProcessing)
                {
                    //Получает данные с сокета
                    mm.qSocket.Receive(mm);
                    //Обработка полученных системных сообщений
                    mm.ProcessSysMessage();
                    //Обработка полученных сообщений
                    mm.ProcessMessage();
                    Thread.Sleep(1);
                }
                mm.qSocket.CloseSocket();
            };

            MainThreadProcMsg          = new Thread(actionMessage);
            MainThreadProcMsg.Priority = ThreadPriority.Normal;
            MainThreadProcMsg.Start(this);

            if (this.BaseMManager)
            {
                Thread ThreadConvertor = null;
                //Основной цикл конвертора
                ParameterizedThreadStart actionThreadConvertor = (object classMM) =>
                {
                    MManager mm = (MManager)classMM;
                    while (MManager.LoopProcessing)
                    {
                        //Отправка
                        mm.Convertor.ProcessConvert();
                        Thread.Sleep(1);
                    }
                    mm.qSocket.CloseSocket();
                };
                ThreadConvertor          = new Thread(actionThreadConvertor);
                ThreadConvertor.Priority = ThreadPriority.Highest;
                ThreadConvertor.Start(this);
            }
        }
コード例 #53
0
        public void AsyncMessageHandlerTest(bool testRepeatOmit = true)
        {
            Console.WriteLine("设置去重:" + testRepeatOmit);

            List <Thread> threadsCollection = new List <Thread>();
            StringBuilder sb = new StringBuilder();
            var           emptyContentCount      = 0;                                //空消息数量(一般是因为去重了)
            var           repeatedMessageCount   = 0;                                //确定去重的消息数量
            var           repeatedRequestMessage = new List <IRequestMessageBase>(); //被去重的请求消息记录

            var dt1 = DateTime.Now;

            //每个线程的测试过程
            ParameterizedThreadStart task = async p =>
            {
                //注意:执行到这里的时候,i可能已经不再是创建对象时的i了。
                var param      = p as object[];
                var threadName = param[0];
                var index      = Convert.ToInt32(param[1]);

                string msgId  = null;
                string openId = dt1.Ticks.ToString();//对每一轮测试进行分组,防止串数据
                if (testRepeatOmit)
                {
                    msgId   = DateTime.Today.Ticks.ToString();
                    openId += "0";
                }
                else
                {
                    //MsgId,保证每次时间不一样
                    msgId = (DateTime.Today.Ticks + index).ToString();
                    //OpenId后缀,可以模拟不同人发送,也可以模拟对人多发:i%10
                    //如果需要测试去重功能,可以将index改为固定值,并且将MsgId设为固定值
                    openId += index.ToString();
                }

                //按钮测试
                var xml = string.Format(string.Format(xmlEvent_ClickFormat, "SubClickRoot_Text"),
                                        ////确保每次时间戳不同
                                        DateTimeHelper.GetWeixinDateTime(DateTime.Now.AddHours(index)),
                                        msgId, openId);

                var timestamp = "itsafaketimestamp";
                var nonce     = "whateveryouwant";
                var signature = Senparc.Weixin.MP.CheckSignature.GetSignature(timestamp, nonce, WeixinAsyncController.Token);
                var postModel = new PostModel()
                {
                    Signature = signature,
                    Timestamp = timestamp,
                    Nonce     = nonce
                };

                WeixinAsyncController targetAsync = new WeixinAsyncController();
                Stream streamAsync = new MemoryStream();
                InitAsync(targetAsync, streamAsync, xml);//初始化

                var dtt1   = DateTime.Now;
                var actual = await targetAsync.Post(postModel) as FixWeixinBugWeixinResult;

                var dtt2 = DateTime.Now;

                Assert.IsNotNull(actual);

                lock (AsyncMessageHandlerTestLock)
                {
                    sb.AppendLine("线程:" + threadName);
                    sb.AppendFormat("开始时间:{0},总时间:{1}ms\r\n", dtt1.ToString("HH:mm:ss.ffff"), (dtt2 - dtt1).TotalMilliseconds);

                    if (string.IsNullOrEmpty(actual.Content))
                    {
                        sb.AppendLine("actual.Content为空!!!!!!!!!!!!!!");
                        emptyContentCount++;
                    }
                    else if (targetAsync.MessageHandler.ResponseMessage is ResponseMessageText)
                    {
                        sb.AppendLine((targetAsync.MessageHandler.ResponseMessage as ResponseMessageText).Content);
                    }

                    if (targetAsync.MessageHandler.MessageIsRepeated)
                    {
                        sb.AppendLine("消息已去重!!!!!!!!!!!!!!!!!!");
                        repeatedRequestMessage.Add(targetAsync.MessageHandler.RequestMessage);
                        repeatedMessageCount++;
                    }

                    sb.AppendLine("RequestMessage数量:" + targetAsync.MessageHandler.CurrentMessageContext.RequestMessages.Count);
                    sb.AppendLine("OpenId:" + targetAsync.MessageHandler.RequestMessage.FromUserName);

                    sb.AppendLine();
                    finishedThreadsCount++;
                }
            };


            for (int i = 0; i < threadsCount; i++)
            {
                Thread thread = new Thread(task)
                {
                    Name = "线程序列:" + i,
                };
                threadsCollection.Add(thread);
                thread.Start(new object[] { thread.Name, i });
            }

            while (finishedThreadsCount < threadsCount)
            {
            }
            var dt2 = DateTime.Now;

            Console.WriteLine("总耗时:{0}ms", (dt2 - dt1).TotalMilliseconds);
            Console.WriteLine("Empty Content Count:" + emptyContentCount);
            Console.WriteLine("Repeated Request Count:" + repeatedMessageCount);

            //如果测试去重,则重复数量应该为[总数-1],否则应该为0
            if (testRepeatOmit)
            {
                Assert.AreEqual(threadsCount - 1, repeatedMessageCount);
            }
            else
            {
                Assert.AreEqual(0, repeatedMessageCount);
            }

            Console.WriteLine(sb.ToString());

            Console.WriteLine("============去重消息关键信息===========");
            foreach (var item in repeatedRequestMessage)
            {
                Console.WriteLine(item.CreateTime + "\t" + item.MsgId + "\t" + item.FromUserName);
            }
        }
コード例 #54
0
        private void TransControl()
        {
            while (true)
            {
                int    length = -1;
                byte[] buffer = new byte[Command_Buffer_Size];
                try
                {
                    length = socketConn.Receive(buffer);
                }
                catch (Exception ex)
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        WriteLog(ex.ToString());
                        WriteLog("连接已断开");
                        snackbar.MessageQueue.Enqueue("连接已断开,请重新连接至服务");

                        button_connect.IsEnabled = true;
                        button_connect.Content   = "尝试连接";

                        ResetAuthenInfo();
                    }));
                    break;
                }

                if (length <= 0)
                {
                    continue;
                }

                byte[] message = new byte[length];
                Array.Copy(buffer, message, length);

                TransCtrl_Message tm = (TransCtrl_Message)Byte2Message(message, "TransCtrl_Message");

                this.Dispatcher.Invoke(new Action(() =>
                {
                    listBox_packetInfo.Items.Insert(0, tm.MessageInfo());
                }));

                if (tm.Flag == Status_Flag.Transmit_Request)
                {
                    string file_length;
                    if (tm.FileLength > 1024 * 1024 * 1024)
                    {
                        double fl = (double)tm.FileLength / (1024 * 1024 * 1024);
                        file_length = fl.ToString("f2") + "GB";
                    }
                    else if (tm.FileLength > 1024 * 1024)
                    {
                        double fl = (double)tm.FileLength / (1024 * 1024);
                        file_length = fl.ToString("f2") + "MB";
                    }
                    else if (tm.FileLength > 1024)
                    {
                        double fl = (double)tm.FileLength / 1024;
                        file_length = fl.ToString("f2") + "KB";
                    }
                    else
                    {
                        file_length = tm.FileLength.ToString() + "B";
                    }

                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        WriteLog("收到文件传输请求");

                        dialogHost_TextBox_FileName.Text   = tm.FileName;
                        dialogHost_TextBox_FileLength.Text = tm.FileLength.ToString();
                        snackbar_RecMessage.IsActive       = true;
                        this.Height += 40;
                    }));
                }

                if (tm.Flag == Status_Flag.Transmit_Allow)
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        WriteLog("对方准备接收");

                        ParameterizedThreadStart pts = new ParameterizedThreadStart(SendFile);
                        Thread threadWatch           = new Thread(pts);
                        threadWatch.IsBackground     = true;
                        threadWatch.Start(SendFileInfo);
                    }));
                }

                if (tm.Flag == Status_Flag.Transmit_Cancel)
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        WriteLog("对方拒绝接收");

                        snackbar.MessageQueue.Enqueue("对方拒绝接收");
                    }));
                    break;
                }

                if (tm.Flag == Status_Flag.Transmit_Over)
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        WriteLog("对方请求校验文件");
                        WriteLog("校验值为" + tm.FileName);
                        snackbar.MessageQueue.Enqueue("正在校验");
                    }));

                    //计算校验值
                    string file_hash = null;
                    using (MD5 md5Hash = MD5.Create())
                    {
                        FileStream fs   = new FileStream(SendFileInfo.FileName, FileMode.Open, FileAccess.Read);
                        byte[]     hash = md5Hash.ComputeHash(fs);
                        file_hash = Convert.ToBase64String(hash);
                    }

                    if (file_hash == tm.FileName)
                    {
                        //回送消息
                        TransCtrl_Message tcm = new TransCtrl_Message(Status_Flag.VerifySuccess, DateTime.Now, null, 0);
                        socketConn.Send(Message2Byte(tcm));

                        this.Dispatcher.Invoke(new Action(() =>
                        {
                            WriteLog("本地校验值为" + file_hash);
                            WriteLog("校验成功");
                            snackbar.MessageQueue.Enqueue("校验成功,文件发送成功");
                        }));
                    }
                    else
                    {
                        //回送消息
                        TransCtrl_Message tcm = new TransCtrl_Message(Status_Flag.VerifyFailed, DateTime.Now, null, 0);
                        socketConn.Send(Message2Byte(tcm));

                        this.Dispatcher.Invoke(new Action(() =>
                        {
                            WriteLog("本地校验值为" + file_hash);
                            WriteLog("校验失败");
                            snackbar.MessageQueue.Enqueue("校验失败,文件发送失败");
                        }));
                    }
                }

                if (tm.Flag == Status_Flag.VerifySuccess)
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        WriteLog("校验成功,文件可用");
                        snackbar.MessageQueue.Enqueue("校验成功,文件可用");
                    }));
                }

                if (tm.Flag == Status_Flag.VerifyFailed)
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        WriteLog("校验失败,文件不可用");
                        snackbar.MessageQueue.Enqueue("校验失败,文件不可用");
                    }));
                }
            }
        }
コード例 #55
0
        public void TestMultiThreaded( )
        {
            const int size = 50000;

            var cache = CreateTimeoutCache <int, int>("LRU Test");

            for (int i = 0; i < size; i++)
            {
                cache.Add(i, i);
            }

            const int threadCount = 2;
            const int hits        = 10000;

            var addThreads    = new Thread [threadCount];
            var removeThreads = new Thread [threadCount];

            ParameterizedThreadStart addThreadStart = o =>
            {
                var rand = new Random(new Guid( ).GetHashCode( ));

                for (int i = 0; i < hits; i++)
                {
                    var randVal = rand.Next(size);

                    int val;
                    cache.TryGetOrAdd(randVal, out val, e => e);
                }
            };

            ParameterizedThreadStart removeThreadStart = o =>
            {
                var rand = new Random(new Guid( ).GetHashCode( ));

                for (int i = 0; i < hits; i++)
                {
                    var randVal = rand.Next(size);

                    cache.Remove(randVal);
                }
            };

            using (ManualResetEvent evt = new ManualResetEvent(false))
            {
                ItemsRemovedEventHandler <int> handler = (sender, args) =>
                {
                    if (cache.Count == 0)
                    {
                        // ReSharper disable once AccessToDisposedClosure
                        evt.Set( );
                    }
                };

                cache.ItemsRemoved += handler;

                for (int i = 0; i < threadCount; i++)
                {
                    addThreads [i] = new Thread(addThreadStart)
                    {
                        IsBackground = true
                    };

                    addThreads [i].Start( );

                    removeThreads [i] = new Thread(removeThreadStart)
                    {
                        IsBackground = true
                    };

                    removeThreads [i].Start( );
                }

                for (int i = 0; i < threadCount; i++)
                {
                    addThreads [i].Join( );
                    removeThreads [i].Join( );
                }

                evt.WaitOne(10000);

                cache.ItemsRemoved -= handler;

                Assert.That(cache.Count, Is.EqualTo(0));
            }
        }
コード例 #56
0
 public static void ExecuteMethodP(ParameterizedThreadStart PTS, object Obj)
 {
     PTS(Obj);
 }
コード例 #57
0
        /// <summary>Downloads bytes from the specified URL and saves them to a file.</summary>
        /// <param name="url">The URL.</param>
        /// <param name="file">The file name.</param>
        /// <param name="days">If the file already exists and was modified during the last so and so days, the download will be bypassed.</param>
        /// <param name="callback">The function to execute once the data has been saved to the file, or a null reference. The argument in the callback function is of type System.String and contains the file name.</param>
        internal static void DownloadAndSaveAsynchronous(string url, string file, double days, ParameterizedThreadStart callback)
        {
            bool download;

            if (File.Exists(file))
            {
                try {
                    DateTime lastWrite = File.GetLastWriteTime(file);
                    TimeSpan span      = DateTime.Now - lastWrite;
                    download = span.TotalDays > days;
                } catch {
                    download = true;
                }
            }
            else
            {
                download = true;
            }
            if (download)
            {
                ThreadStart start = new ThreadStart(
                    () => {
                    try {
                        byte[] bytes     = DownloadBytesFromUrl(url);
                        string directory = Path.GetDirectoryName(file);
                        try {
                            Directory.CreateDirectory(directory);
                            File.WriteAllBytes(file, bytes);
                        } catch (Exception ex) {
                            Debug.AddMessage(Debug.MessageType.Warning, false, "Error writing file " + file + ": " + ex.Message);
                        }
                        if (callback != null)
                        {
                            callback.Invoke(file);
                        }
                    } catch { }
                }
                    );
                Thread thread = new Thread(start);
                thread.IsBackground = true;
                thread.Start();
            }
            else if (callback != null)
            {
                callback.Invoke(file);
            }
        }
コード例 #58
0
        private static Texture2D ThreadedScale(Texture2D tex, int newWidth, int newHeight, bool useBilinear, bool flipH, bool flipV)
        {
            texColors = tex.GetPixels();
            newColors = new Color[newWidth * newHeight];
            if (useBilinear)
            {
                ratioX = 1.0f / ((float)newWidth / (tex.width - 1));
                ratioY = 1.0f / ((float)newHeight / (tex.height - 1));
            }
            else
            {
                ratioX = ((float)tex.width) / newWidth;
                ratioY = ((float)tex.height) / newHeight;
            }
            w  = tex.width;
            w2 = newWidth;
            var cores = Mathf.Min(SystemInfo.processorCount, newHeight);
            var slice = newHeight / cores;

            finishCount = 0;
            if (mutex == null)
            {
                mutex = new Mutex(false);
            }
            if (cores > 1)
            {
                int        i = 0;
                ThreadData threadData;
                for (i = 0; i < cores - 1; i++)
                {
                    threadData = new ThreadData(slice * i, slice * (i + 1));
                    ParameterizedThreadStart ts = useBilinear ? new ParameterizedThreadStart(BilinearScale) : new ParameterizedThreadStart(PointScale);
                    Thread thread = new Thread(ts);
                    thread.Start(threadData);
                }
                threadData = new ThreadData(slice * i, newHeight);
                if (useBilinear)
                {
                    BilinearScale(threadData);
                }
                else
                {
                    PointScale(threadData);
                }
                while (finishCount < cores)
                {
                    Thread.Sleep(1);
                }
            }
            else
            {
                ThreadData threadData = new ThreadData(0, newHeight);
                if (useBilinear)
                {
                    BilinearScale(threadData);
                }
                else
                {
                    PointScale(threadData);
                }
            }



            tex.Resize(newWidth, newHeight);
            tex.SetPixels(newColors);
            tex.Apply();
            Texture2D orig = new Texture2D(tex.width, tex.height);

            if (flipV)
            {
                int xN = tex.width;
                int yN = tex.width;

                for (int i = 0; i < xN; i++)
                {
                    for (int j = 0; j < yN; j++)
                    {
                        // tex.SetPixel(xN - i - 1, j, orig.GetPixel(i, j));
                        orig.SetPixel(i, yN - j - 1, tex.GetPixel(i, j));
                    }
                }
                orig.Apply();
            }
            else if (flipH)
            {
                int xN = tex.width;
                int yN = tex.width;

                for (int i = 0; i < xN; i++)
                {
                    for (int j = 0; j < yN; j++)
                    {
                        // tex.SetPixel(xN - i - 1, j, orig.GetPixel(i, j));
                        orig.SetPixel(xN - i - 1, j, tex.GetPixel(i, j));
                    }
                }
                orig.Apply();
            }
            else
            {
                orig = tex;
            }
            return(orig);
        }
コード例 #59
0
 public void QueueIdle(ParameterizedThreadStart method)
 {
     IdleThreadQueue.Instance.Enqueue(method, null);
 }
コード例 #60
0
 // Constructors
 public Thread(ParameterizedThreadStart start);