コード例 #1
1
    protected override Result RunCommand(RhinoDoc doc, RunMode mode)
    {
      m_doc = doc;

      m_window = new Window {Title = "Object ID and Thread ID", Width = 500, Height = 75};
      m_label = new Label();
      m_window.Content = m_label;
      new System.Windows.Interop.WindowInteropHelper(m_window).Owner = Rhino.RhinoApp.MainWindowHandle();
      m_window.Show();


      // register the rhinoObjectAdded method with the AddRhinoObject event
      RhinoDoc.AddRhinoObject += RhinoObjectAdded;

      // add a sphere from the main UI thread.  All is good
      AddSphere(new Point3d(0,0,0));

      // add a sphere from a secondary thread. Not good: the rhinoObjectAdded method
      // doesn't work well when called from another thread
      var add_sphere_delegate = new Action<Point3d>(AddSphere);
      add_sphere_delegate.BeginInvoke(new Point3d(0, 10, 0), null, null);

      // handle the AddRhinoObject event with rhinoObjectAddedSafe which is
      // desgined to work no matter which thread the call is comming from.
      RhinoDoc.AddRhinoObject -= RhinoObjectAdded;
      RhinoDoc.AddRhinoObject += RhinoObjectAddedSafe;

      // try again adding a sphere from a secondary thread.  All is good!
      add_sphere_delegate.BeginInvoke(new Point3d(0, 20, 0), null, null);

      doc.Views.Redraw();

      return Result.Success;
    }
コード例 #2
1
 public static DataReaderObservableRunner RunAsync(IDbCommand command, IObserver<IDictionary<string, object>> observer)
 {
     var instance = new DataReaderObservableRunner(command, observer);
     var asyncAction = new Action(instance.Run);
     asyncAction.BeginInvoke(asyncAction.EndInvoke, null);
     return instance;
 }
コード例 #3
0
ファイル: CalendarTest.cs プロジェクト: datttit/SyncMLDotNet
        public void TestSettingsInThread()
        {
            DateTime now = DateTime.Now;

            SyncItem syncItem;

            System.Action saveAnchor = () =>
            {
                SyncSettingsBase settings = OutlookSyncSettings.Default;
                syncItem = OutlookSyncSettings.Default.CalendarSyncItem;
                syncItem.LastAnchorTime = now;
                settings.Save();
            };

            IAsyncResult result = saveAnchor.BeginInvoke(null, null);

            saveAnchor.EndInvoke(result);

            System.Threading.Thread.Sleep(100);
            OutlookSyncSettings.Default.Reload();
            Assert.AreEqual(now, OutlookSyncSettings.Default.CalendarSyncItem.LastAnchorTime);

            now = DateTime.Now;
            IAsyncResult result2 = saveAnchor.BeginInvoke(null, null);

            saveAnchor.EndInvoke(result2);

            System.Threading.Thread.Sleep(100);
            OutlookSyncSettings.Default.Reload();
            Assert.AreEqual(now, OutlookSyncSettings.Default.CalendarSyncItem.LastAnchorTime);
        }
コード例 #4
0
 public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
 {
     culture = Thread.CurrentThread.CurrentCulture;
     principal = Thread.CurrentPrincipal;
     processRequest = ProcessRequest;
     return processRequest.BeginInvoke(context, cb, extraData);
 }
コード例 #5
0
 public void CalculateSize()
 {
     _calculateAsync = () => {
         Size = DirSize(Path);
     };
     _calculateAsync.BeginInvoke(_calculateAsync.EndInvoke, null);
 }
コード例 #6
0
        private void DownloadButton_Click(object sender, EventArgs e)
        {
            DownloadButton.Enabled = false;

            ChangesTextBox.AppendText(Environment.NewLine);
            ChangesTextBox.AppendText("Downloading..." + Environment.NewLine);

            var downloadAction = new Action(() =>
            {
                Parallel.ForEach(m_newPatches, patch =>
                {
                    var localPath = PatchManager.GetPatchFilePath(m_definition, patch.Name);
                    var directory = PatchManager.GetPatchDirectoryPath(m_definition);

                    Paths.EnsureDirectoryExists(directory);
                    GitHubApi.DownloadFile(patch.DownloadUrl, localPath);

                    this.UpdateUI(() => ChangesTextBox.AppendText(patch.Name + " done." + Environment.NewLine));
                });

                this.UpdateUI(() =>
                {
                    DialogResult = DialogResult.OK;
                });
            });
            downloadAction.BeginInvoke(null, null);
        }
コード例 #7
0
        private void plotButton_click(object sender, RoutedEventArgs e)
        {
            if (graphBitmap == null)
            {
                graphBitmap = new WriteableBitmap(pixelWidth, pixelHeight, dpiX, dpiY, PixelFormats.Gray8, null);
            }
            Action doPlotButtonWorkAction = new Action(doPlotButtonWork);
            doPlotButtonWorkAction.BeginInvoke(null, null);
            #region 注释掉的内容
            //int byetePerPixel = (graphBitmap.Format.BitsPerPixel + 7) / 8;
            //int stride = byetePerPixel * graphBitmap.PixelWidth;
            //int dataSize = stride * graphBitmap.PixelHeight;
            //byte[] data = new byte[dataSize];

            //Stopwatch watch = new Stopwatch();

            ////generateGraphData(data);
            ////新建线程
            //Task first = Task.Factory.StartNew(()=>generateGraphData(data,0,pixelWidth/8));
            //Task second = Task.Factory.StartNew(() => generateGraphData(data, pixelWidth / 8, pixelWidth / 4));
            //Task first1 = Task.Factory.StartNew(() => generateGraphData(data, pixelWidth / 4, pixelWidth / 2));
            //Task second1 = Task.Factory.StartNew(() => generateGraphData(data, pixelWidth / 2, pixelWidth));
            //Task.WaitAll(first, second,first1,second1);
            //duration.Content = string.Format("Duration (ms):{0}", watch.ElapsedMilliseconds);
            //graphBitmap.WritePixels(new Int32Rect(0, 0, graphBitmap.PixelWidth, graphBitmap.PixelHeight), data, stride, 0);
            //graphImage.Source = graphBitmap;
            #endregion
        }
コード例 #8
0
ファイル: MainWindow.xaml.cs プロジェクト: yjl617/QRreader
 public void DecodeQR(System.Drawing.Image img)
 {
     textbox.Text = "正在解析";
     Action action = new Action(delegate ()
     {
         string mess = "";
         try
         {
             DllHelper helper = new DllHelper();
             System.Drawing.Bitmap bmap = new System.Drawing.Bitmap(img);
             string deCodeAss = "ThoughtWorks.QRCode.Codec.QRCodeDecoder.DeCodeImg";
             var destring = helper.InvokQR(deCodeAss, new object[] { bmap, Encoding.UTF8 });
            mess = destring.ToString();
         }
         catch (Exception ex)
         {
             mess = "解析失败,请重试";
         }
         Dispatcher.BeginInvoke(new Action(delegate ()
         {
             textbox.Text = mess;
         }), null);
     });
     action.BeginInvoke(null, null);
 }
コード例 #9
0
    public void BeginStreaming()
    {
      try
      {
        request = new CampfireRequest(this.site)
            .CreateRequest(this.site.ApiUrlBuilder.Stream(this.room.ID), HttpMethod.GET);
        request.Timeout = -1;

        // yes, this is needed. regular authentication using the Credentials property does not work for streaming
        string token = string.Format("{0}:X", this.site.ApiToken);
        string encoding = Convert.ToBase64String(Encoding.UTF8.GetBytes(token));
        request.Headers.Add("Authorization", "Basic " + encoding);

        response = request.GetResponse();
        responseStream = response.GetResponseStream();
        reader = new StreamReader(responseStream, Encoding.UTF8);

        del = new Action(() =>
        {
          ReadNextMessage(reader);
        });

        del.BeginInvoke(LineRead, null);
      }
      catch
      {
        Thread.Sleep(2500);
        BeginStreaming();
      }
    }
コード例 #10
0
	/* expected exit code: 255 */
	static void Main (string[] args)
	{
		if (Environment.GetEnvironmentVariable ("TEST_UNHANDLED_EXCEPTION_HANDLER") != null)
			AppDomain.CurrentDomain.UnhandledException += (s, e) => {};

		ManualResetEvent mre = new ManualResetEvent (false);

		var a = new Action (() => { try { throw new CustomException (); } finally { mre.Set (); } });
		var ares = a.BeginInvoke (null, null);

		if (!mre.WaitOne (5000))
			Environment.Exit (2);

		try {
			a.EndInvoke (ares);
			Environment.Exit (4);
		} catch (CustomException) {
			/* expected behaviour */
			Environment.Exit (255);
		} catch (Exception ex) {
			Console.WriteLine (ex);
			Environment.Exit (3);
		}

		Environment.Exit (5);
	}
コード例 #11
0
        private void CalculateTwoSums(int lowerBound, int upperBound)
        {
            for (int currentSum = lowerBound; currentSum <= upperBound; currentSum++)
            {
                Action twoSum = new Action(() =>
                {
                    foreach (long value in this.hashTable.Values)
                    {
                        if (!distinctSums.ContainsKey(currentSum))
                        {
                            long searchValue = currentSum - value;
                            long otherValue = 0;

                            if (searchValue != value && this.hashTable.TryGetValue(searchValue, out otherValue))
                            {
                                distinctSums.TryAdd(currentSum, new KeyValuePair<long, long>(value, otherValue));
                            }
                        }
                    }

                    if (currentSum == upperBound)
                    {
                        this.Complete.TrySetResult(true);
                    }
                });

                twoSum.BeginInvoke(null, null);
            }
        }
コード例 #12
0
        public void BeginUpload(Action<FSUploadResultEntity, Exception> uploadCallback, int timeout)
        {
            UploadCallBack = uploadCallback;

            Action<FSUploadEntity> asyncUploadAction = new Action<FSUploadEntity>((fsUpload) =>
            {
                StorageServer storageServer = TrackerClient.GetStorageServer();
                if (storageServer == null)
                {
                    InnerEx = new Exception("FSUploadTransaction.BeginTTSSynth(): Failed to get Storage server address: Please check ths fdfs storage's config and the fdfs tracker is running.");
                    return;
                }

                Exception outputCallbackEx = null;
                StorageClient.Upload(storageServer, uploadEntity.FileExtName, uploadEntity.FileSize, uploadEntity.FileBuffer, string.Empty, (filePathArray) =>
                {
                    try
                    {
                        FilePath = string.Format("{0}/{1}", filePathArray[0], filePathArray[1]);   // 0: groupName, 1:fileName
                    }
                    catch (Exception ex2)
                    {
                        string err = string.Format("FSUploadTransaction.BeginUpload: Exception when executing OutputCallback of StorageClient.Upload(), FileName={0}, storageServer={1}", uploadEntity.FileName, storageServer.IP);
                        outputCallbackEx = new Exception(err, ex2);
                    }
                });

                if(null != outputCallbackEx)
                {
                    InnerEx = outputCallbackEx;
                }
            });

            asyncUploadAction.BeginInvoke(uploadEntity, new AsyncCallback(CallbackForAsyncAction), this);
        }
コード例 #13
0
        public void StartTracing()
        {
            refCount++;
            if (refCount > 1)
            {
                return;
            }

            stopProcessing = false;
            StartSession();

            logFile                     = new EventTraceLogfile();
            logFile.LoggerName          = this.eventLogSessionName;
            logFile.EventRecordCallback = EventRecordCallback;

            logFile.ProcessTraceMode = EventRecord | RealTime;
            this.traceHandle         = NativeMethods.OpenTrace(ref logFile);

            int error = Marshal.GetLastWin32Error();

            if (error != 0)
            {
                throw new System.ComponentModel.Win32Exception(error);
            }

            processEventsDelegate = new System.Action(ProcessTraceInBackground);
            asyncResult           = processEventsDelegate.BeginInvoke(null, this);
        }
コード例 #14
0
        public SchedulerTask RunTask(Func<TaskFactory, SchedulerTask> fn)
        {
            progressBar1.Value = 0;
            label1.Text = richTextBox1.Text = "";


            var factory = ProgramContext.Container.Resolve<TaskFactory>();
            task = fn(factory);
            task.TaskStarted += (t) => { };
            task.TaskFinished += (t) => { };
            task.ScriptStarted += (t, s) => { };
            task.ScriptFinished += (t, s) => { };
            task.ScriptCustomEvent += (t, s, o) => { };
            task.Progress.Update +=
                (p) => this.Invoke(new Action(
                                       () =>
                                       {
                                           label1.Text = p.Message;
                                           progressBar1.Value = p.Completeness;
                                           richTextBox1.Text += p.Message + Environment.NewLine;

                                           richTextBox1.SelectionStart = richTextBox1.Text.Length;
                                           richTextBox1.ScrollToCaret();
                                       }));

            var asyncRunner = new Action(
                () =>
                {
                    factory.RunTaskUntilFinished(task);
                    if (OnTaskComplete != null) OnTaskComplete(this, EventArgs.Empty);
                });
            asyncRunner.BeginInvoke(null, null);
            return task;
        }
コード例 #15
0
 public static void Main(string[] args)
 {
     var cooldown = TASK_COOLDOWN;
     if (args.Length > 0) {
         cooldown = int.Parse (args [0]);
         Console.WriteLine ("Cooldown is {0} ms", cooldown);
     }
     while (true) { // catch ctrl+c
         if (Games.Count < Environment.ProcessorCount) {
             GameType type;
             GetRandomTask (out type);
             Console.WriteLine ("Enqueing type " + type);
             var action = new Action<GameType> (RunGame);
             Games.Enqueue (new GameAction () {
                 GameType = type,
                 Delegate = action,
                 Result = action.BeginInvoke (type, null, null) // run game here
             });
         } else {
             var game = Games.Dequeue ();
             Console.WriteLine ("Waiting for {0} to complete", game.GameType);
             try {
                 game.Delegate.EndInvoke (game.Result); // sync here
             } catch (Exception ex) {
                 Console.WriteLine ("Got exception here, okay i guess... " + ex.GetType ());
                 Console.WriteLine (ex);
             }
         }
     }
 }
コード例 #16
0
 private void button1_Click(object sender, EventArgs e)
 {
     System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
     //邮件
     System.Action handler = new System.Action(this.money); //定义委托
     handler.BeginInvoke(null, null);                       //异步调用
 }
コード例 #17
0
ファイル: Loading.cs プロジェクト: samualtang/PMSolution
        /// <summary>
        /// 传入一个窗体,触发遮罩层的时候所有控件都禁止
        ///
        /// </summary>
        /// <param name="f1">窗体</param>
        /// <param name="action">delegate () { 方法名(); }</param>
        public static async void Masklayer(Form f1, System.Action action)
        {
            //传入函数分支运行
            IAsyncResult result = action.BeginInvoke(null, null);

            //函数分支创建一个遮罩层
            await MaskControls(f1, result);
        }
コード例 #18
0
ファイル: base.cs プロジェクト: Exclr8/CloudCore
        private static void CheckoutFileIfRequired(_DTE dte, String fileName)
        {
            _checkOutAction = (String fn) => dte.SourceControl.CheckOutItem(fn);

            var sc = dte.SourceControl;
            if (sc != null && sc.IsItemUnderSCC(fileName) && !sc.IsItemCheckedOut(fileName))
                _checkOutAction.EndInvoke(_checkOutAction.BeginInvoke(fileName, null, null));
        }
コード例 #19
0
ファイル: Scheduler.cs プロジェクト: Xileck/tibiaapi
 public static void AddTask(Delegate ev, object[] paramArray, int time)
 {
     lock (addEventLock)
     {
         Action<Delegate, object[], int> myDelegate = new Action<Delegate, object[], int>(AddTaskDelay);
         myDelegate.BeginInvoke(ev, paramArray, time, null, null);
     }
 }
コード例 #20
0
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            var message = Message.Get(context);

            var MarkAsReadDelegate = new Action<EmailMessage>(MarkAsRead);
            context.UserState = MarkAsReadDelegate;
            return MarkAsReadDelegate.BeginInvoke(message, callback, state);            
        }
コード例 #21
0
ファイル: Scheduler.cs プロジェクト: henriqueuller/sharpot
 public static void AddTask(Action action, object[] paramArray, int delayInMilliseconds)
 {
     lock (addEventLock)
     {
         Action<Action, int> myDelegate = new Action<Action, int>(AddTaskDelay);
         myDelegate.BeginInvoke(action, delayInMilliseconds, null, null);
     }
 }
コード例 #22
0
ファイル: RemoteAgent.cs プロジェクト: kainhong/CurrencyStore
 public void BatchSave_Info(List<Entity.CurrencyInfo> values)
 {
     var action = new Action(() => { service.BatchSave_Info(values); });
     action.BeginInvoke((ar) =>
     {
         action.EndInvoke(ar);
         ServerInstrumentation.Current.Queue(-1);
     }, action);
 }
コード例 #23
0
        protected override void OnListBoxAttached()
        {
            base.OnListBoxAttached();

            Items.Clear();
            _project = ServiceContext.Projects.Lookup(ServiceContext.DefaultProjectId);
            var action = new Action(_project.BuildTypes.Refresh);
            action.BeginInvoke(OnProjectBuildTypesUpdated, action);
        }
コード例 #24
0
	/* expected exit code: 0 */
	static void Main (string[] args)
	{
		var action = new Action (Delegate);
		var ares = action.BeginInvoke (Callback, null);

		Thread.Sleep (5000);

		Environment.Exit (1);
	}
コード例 #25
0
ファイル: GraphWindow.xaml.cs プロジェクト: niuniuliu/CSharp
        private void plotButton_Click(object sender, RoutedEventArgs e)
        {
            if (graphBitmap == null)
            {
                graphBitmap = new WriteableBitmap(pixelWidth, pixelHeight, dpiX, dpiY, PixelFormats.Gray8, null);
            }

            Action doPlotButtonWorkAction = new Action(doPlotButtonWork);
            doPlotButtonWorkAction.BeginInvoke(null, null);
        }
コード例 #26
0
        public void ExtractFeaturesAsync(ISoundSignalReader signal, Action<List<double[]>> action,
            SignalVisitor voiceVisitor = null)
        {
            Action<List<double[]>> addfeatures = features =>
            {
                action.BeginInvoke(features, null, null);
            };

            ExtractFeaturesInternalUsingVad(signal, addfeatures, voiceVisitor);
        }
コード例 #27
0
        internal static void LoginAsAdmin([NotNull] Instance instance, [NotNull] Window owner, [CanBeNull] string pageUrl = null, [CanBeNull] string browser = null, [CanBeNull] string[] parameters = null)
        {
            Assert.ArgumentNotNull(instance, "instance");
              Assert.ArgumentNotNull(owner, "owner");

              if (!InstanceHelperEx.PreheatInstance(instance, owner, true))
              {
            return;
              }

              // Generating unique url to authenticate user
              var url = CoreInstanceAuth.GenerateAuthUrl();
              var destFileName = CoreInstanceAuth.CreateAuthFile(instance, url);

              // Schedule deletion of the file
              var async = new Action(() => DeleteFile(destFileName));
              async.BeginInvoke(null, null);

              var userName = CoreAppSettings.AppLoginAsAdminUserName.Value;
              var isFrontEnd = false;
              var clipboard = pageUrl == "$(clipboard)";
              if (clipboard)
              {
            pageUrl = string.Empty;
              }

              if (string.IsNullOrEmpty(pageUrl))
              {
            var value = CoreAppSettings.AppLoginAsAdminPageUrl.Value;
            if (!string.IsNullOrEmpty(value) && !value.EqualsIgnoreCase("/sitecore") && !value.EqualsIgnoreCase("sitecore"))
            {
              pageUrl = value;
              if (!value.StartsWith("/sitecore/"))
              {
            isFrontEnd = true;
              }
            }
              }

              var querystring = (string.IsNullOrEmpty(pageUrl) ? string.Empty : "&page=" + pageUrl) + (string.IsNullOrEmpty(userName) || userName.EqualsIgnoreCase("admin") || userName.EqualsIgnoreCase("sitecore\\admin") ? string.Empty : "&user="******"?" + querystring;
              }

              if (clipboard)
              {
            Clipboard.SetDataObject(instance.GetUrl(url + querystring));
              }
              else
              {
            InstanceHelperEx.BrowseInstance(instance, owner, url + querystring, isFrontEnd, browser, parameters);
              }
        }
コード例 #28
0
ファイル: Servidor.cs プロジェクト: pcmind/yolo-octo-sansa
 public static bool AsyncCallAndWait(Action action)
 {
     IAsyncResult result = action.BeginInvoke(null, null);
     try {
         action.EndInvoke(result);
     }
     catch (Exception) {
         return false;
     }
     return true;
 }
コード例 #29
0
 public static void RunAsync(Action action, string indexName)
 {
     try
     {
         action.BeginInvoke(null, null);
     }
     catch (Exception ex)
     {
         Log.Error("Error occurred while updating spellchecker dictionary for index " + indexName, ex, typeof(IndexingEventHandler));
     }
 }
コード例 #30
0
ファイル: ShellViewModel.cs プロジェクト: cbradley857/Winfy
        private void UpdateView()
        {
            try {
                var status = _SpotifyController.GetStatus();
                var track  = _SpotifyController.GetSongName();
                var artist = _SpotifyController.GetArtistName();
                var fade   = (status != null && status.Playing);

                if (fade)
                {
                    OnCoverDisplayFadeOut();
                }

                HasTrackInformation = (!string.IsNullOrEmpty(track) || !string.IsNullOrEmpty(artist));
                CurrentTrack        = string.IsNullOrEmpty(track) ? "-" : track;
                CurrentArtist       = string.IsNullOrEmpty(artist) ? "-" : artist;

                CanPlayPause    = _SpotifyController.IsSpotifyOpen();
                CanPlayPrevious = _SpotifyController.IsSpotifyOpen();
                CanPlayNext     = _SpotifyController.IsSpotifyOpen();

                if (_SpotifyController.IsSpotifyOpen() && !string.IsNullOrEmpty(track) && !string.IsNullOrEmpty(artist))
                {
                    if (_Settings.DisableAnimations)
                    {
                        CoverImage = NoCoverUri;                         //Reset cover image, no cover is better than an old one
                    }
                    var updateCoverAction = new Action(() => {
                        var coverUri = _CoverService.FetchCover(artist, track);
                        if (string.IsNullOrEmpty(coverUri))
                        {
                            coverUri = UnknownCoverUri;
                        }
                        CoverImage = coverUri;
                        if (fade)
                        {
                            OnCoverDisplayFadeIn();
                        }
                    });
                    updateCoverAction.BeginInvoke(UpdateCoverActionCallback, null);
                }
                else
                {
                    CoverImage = NoCoverUri;
                    if (fade)
                    {
                        OnCoverDisplayFadeIn();
                    }
                }
            }
            catch (Exception exc) {
                _Logger.FatalException("UpdateView() failed hard", exc);
            }
        }
コード例 #31
0
ファイル: SnippetDataSource.cs プロジェクト: Helen1987/edu
        public ObservableCollection<Snippet> GetSnippets()
        {
            Action loadDelegate = new Action(delegate()
            {
                m_snippets.Add(new Snippet("Header", "Header information", "This is the header"));
                m_snippets.Add(new Snippet("Footer", "Footer information", "This is the footer"));
            });
            loadDelegate.BeginInvoke(null, null);

            return m_snippets;
        }
コード例 #32
0
 public static Task OnClick(this Control control, Action<Task<EventArgs>> handler)
 {
     Action<Task<EventArgs>> eventHandler = (e) => { };
     return control.UntilClick().ContinueWith(eventHandler = (e) =>
     {
         Task
             .Factory
             .FromAsync(handler.BeginInvoke(e, null, null), handler.EndInvoke)
             .ContinueWith((temp) => control.UntilClick().ContinueWith(eventHandler));
     });
 }
コード例 #33
0
		public void Start(IWin32Window owner, int fileCount, Action action) {
			progressBar.Maximum = fileCount;
			Show(owner);

			action.BeginInvoke(
					ar => {
						action.EndInvoke(ar);
						Action hideAction = EndProgress;
						Invoke(hideAction);
					}, null);
		}
コード例 #34
0
	/* expected exit code: 255 */
	static void Main (string[] args)
	{
		if (Environment.GetEnvironmentVariable ("TEST_UNHANDLED_EXCEPTION_HANDLER") != null)
			AppDomain.CurrentDomain.UnhandledException += (s, e) => {};

		var action = new Action (Delegate);
		var ares = action.BeginInvoke (Callback, null);

		Thread.Sleep (5000);

		Environment.Exit (1);
	}
コード例 #35
0
ファイル: CloudDBTool.cs プロジェクト: lzcj4/Game28
 public void Restore(string cloudName)
 {
     Action action = new Action(() =>
     {
         if (DownloadFromCloud(cloudName))
         {
             MergeDB(cloudName);
             MessageBox.Show("云还原成功");
         }
     });
     action.BeginInvoke((ar) => action.EndInvoke(ar), action);
 }
コード例 #36
0
        /// <summary>
        /// Обновление цен и проверка обменов
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void PriceCorrectTimer(object sender, ElapsedEventArgs e)
        {
            WriteMessage("Таймер", MessageType.Timer);

            //выставитьToolStripMenuItem_Click(sender, e);
            UpdatePriceDelegateAction.BeginInvoke(CallbackUpdater, null);

            if (autoConfirmTrades)
            {
                var info = CLIENT1.CountItemsToTransfer(cfg.key);
                if (info?.getCount > 0)
                {
                    tradeWorker.AcceptTrade(TypeTrade.OUT);
                }
                if (info?.outCount > 0)
                {
                    tradeWorker.AcceptTrade(TypeTrade.IN);
                }
                //AcceptTradeAction.Invoke();
                //AcceptMobileOrdersAction.Invoke();
            }
        }
コード例 #37
0
        public void Can_Write_ToSheet_From_Many_Threads()
        {
            Worksheet        currentSheet = null;
            ApplicationClass excel        = null;

            using (ExcelOutputWriter writer = new ExcelOutputWriter(null, ExcelOptions.None))
            {
                string ExtCol1 = "ext1";
                string ExtCol2 = "ext2";

                writer.SetCurrentSheet(mySearchHeader);
                currentSheet = writer.myCurrentSheet;

                excel = writer.myExcel;

                int LinesToWrite = 30;

                System.Action acc = () =>
                {
                    while (true)
                    {
                        if (LinesToWrite <= 0)
                        {
                            break;
                        }

                        writer.PrintRow("none", () => new List <string> {
                            ExtCol1, ExtCol2
                        },
                                        Thread.CurrentThread.ManagedThreadId.ToString(), LinesToWrite.ToString(), "field3", "field4");

                        Interlocked.Decrement(ref LinesToWrite);
                    }
                };

                for (int i = 0; i < 5; i++)
                {
                    acc.BeginInvoke(null, null);
                }
                while (LinesToWrite > 0)
                {
                    Thread.Sleep(50);
                }
                Console.WriteLine("Did enqeue all items");
            }

            Assert.IsNotNull(currentSheet.get_Range("B34", Type.Missing).Value2);
            excel.Quit();
        }
コード例 #38
0
        public static void RunParallel(this Action <int> task, int runCount)
        {
            // Check the progress only so often to reduce the lock overhead.
            const int batchSize = 10;

            var progress = 0;

            System.Action allRuns = delegate
            {
                while (true)
                {
                    // Get the next batch.
                    int item;
                    lock (task)
                    {
                        item      = progress;
                        progress += batchSize;
                    }
                    // Run the batch.
                    for (var i = item; i < item + batchSize; ++i)
                    {
                        if (i >= runCount)
                        {
                            return;
                        }
                        task(i);
                    }
                }
            };


            var threadCount = Environment.ProcessorCount;

            // Start the tasks.
            var results = new IAsyncResult[threadCount];

            for (var i = 0; i < threadCount; ++i)
            {
                results[i] = allRuns.BeginInvoke(null, null);
            }

            // Wait for all tasks to complete
            for (var i = 0; i < threadCount; ++i)
            {
                allRuns.EndInvoke(results[i]);
            }
        }
コード例 #39
0
        public void SendMsg(byte[] data)
        {
            // 得到包体的数组
            byte[] Senddata = MakeData(data);

            lock (m_sendQueue)
            {
                // 把数据包加入队列
                m_sendQueue.Enqueue(Senddata);

                //启动委托
                if (m_checkSendQueue != null)
                {
                    m_checkSendQueue.BeginInvoke(null, null);
                }
            }
        }
コード例 #40
0
ファイル: WaitingDialog.cs プロジェクト: balihb/basenji
        private void BeginWaiting()
        {
            System.Action act = delegate {
                T tmp = default(T);
                while (!canceled && !waitFunc(out tmp))
                {
                    Thread.Sleep(1000);
                }

                if (!canceled)
                {
                    Application.Invoke(delegate {
                        Value = tmp;
                        Respond(ResponseType.Ok);
                    });
                }
            };
            act.BeginInvoke(null, null);
        }
コード例 #41
0
 protected void SetupTest()
 {
     CyPhyGUIs.CyPhyDirectory.EnsureEmptyDirectory(TestModelDir);
     StartMetaLinkBridge();
     try
     {
         System.Action d   = (System.Action)CopyTestModel;
         var           res = d.BeginInvoke(null, null);
         WaitForMetaLinkBridgeToBeReady();
         StartTestingClient();
         d.EndInvoke(res);
     }
     catch
     {
         KillMetaLink();
         lock (metalinkLogStream)
             metalinkLogStream.Dispose();
         throw;
     }
 }
コード例 #42
0
ファイル: Form1-ms-excel.cs プロジェクト: zyb2013/ARK
        /////////////////////////////////////////////////////////////////////////

        private void OnCreateXMLFile(object sender, EventArgs e)
        {
            this.skinButton2.Text    = "正在生成文件,请稍等...";
            this.skinButton2.Enabled = false;

            //////////////////////////////////////////////////////////////////////

            //Thread xStructThread = new Thread(CreateStructThreadFunc);
            //Thread xIniThread = new Thread(CreateIniThreadFunc);

            //xStructThread.Start();
            //xIniThread.Start();
            System.Action xStructAction = new System.Action(CreateStructThreadFunc);
            System.Action xIniAction    = new System.Action(CreateIniThreadFunc);

            xStructAction.BeginInvoke(new AsyncCallback(CreateXMLCallBack), null);
            xIniAction.BeginInvoke(new AsyncCallback(CreateXMLCallBack), null);

            ////////////////////////////////////////////////////////
        }
コード例 #43
0
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            LoadAuthentication(context);
            boardidinput = BoardId.Get(context);

            CreateListDelegate = new System.Action(_CreateLists);

            return(CreateListDelegate.BeginInvoke(callback, state));



            /*  var board = new Board(boardid, auth);
             * //board.Name = "UiPath Board";
             * board.Lists.Add("Uiboard");
             * board.Lists.Refresh();
             * var list = board.Lists.First();
             * list.Cards.Add("UIpath card");
             */

            // ITrelloFactory factory = new TrelloFactory();
        }
コード例 #44
0
        public void OpenTraceLog(string logFileName)
        {
            stopProcessing              = false;
            logFile                     = new EventTraceLogfile();
            logFile.BufferCallback      = TraceEventBufferCallback;
            logFile.EventRecordCallback = EventRecordCallback;
            logFile.ProcessTraceMode    = EventRecord;
            logFile.LogFileName         = logFileName;

            this.traceHandle = NativeMethods.OpenTrace(ref logFile);

            if (INVALID_HANDLE_VALUE == traceHandle)
            {
                int error = Marshal.GetLastWin32Error();
                if (error != 0)
                {
                    throw new System.ComponentModel.Win32Exception(error);
                }
            }

            processEventsDelegate = new System.Action(ProcessTraceInBackground);
            asyncResult           = processEventsDelegate.BeginInvoke(null, this);
        }
コード例 #45
0
ファイル: Light.cs プロジェクト: ewin66/wholePivas
        /// <summary>
        /// 带超时时间的方法调用
        /// </summary>
        /// <param name="action"></param>
        /// <param name="timeoutMilliseconds"></param>
        void CallWithTimeout(System.Action action, int timeoutMilliseconds)
        {
            try
            {
                if (action == null)
                {
                    return;
                }

                Thread        threadToKill  = null;
                System.Action wrappedAction = () =>
                {
                    threadToKill = Thread.CurrentThread;
                    action();
                };

                IAsyncResult result = wrappedAction.BeginInvoke(null, null);
                if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
                {
                    wrappedAction.EndInvoke(result);
                }
                else
                {
                    threadToKill.Abort();
                    throw new TimeoutException();
                }
            }
            catch (TimeoutException)
            {
                //action.Method.Name获取方法名,匿名时采用<父函数名>b_0_0
                InternalLogger.Log.Error(String.Format("调用{0}方法超过{1}毫秒,请检查与设备通信链路。", action.Method.Name, timeoutMilliseconds));
            }
            catch (Exception ex)
            {
                InternalLogger.Log.Error("带超时时间的方法调用出错:" + ex.Message);
            }
        }
コード例 #46
0
 private void button2_Click(object sender, EventArgs e)
 {
     System.Action handler = new System.Action(this.money); //定义委托
     handler.BeginInvoke(null, null);                       //异步调用
 }
コード例 #47
0
ファイル: Fixture.cs プロジェクト: zmp2000/nhibernate-core
        public void Test()
        {
            // WARNING: This test case makes use of reflection resulting in failures if internals change, but reflection was needed to allow for simulation.
            // This test simulates a heavy load on the QueryPlanCache by making it use a SoftLimitMRUCache instance with a size of 1 instead of the default of 128.
            // Since this cache moves the most recently used query plans to the top, pushing down the less used query plans until they are removed from the cache,
            // the smaller the size of the cache the sooner the query plans will be dropped, making it easier to simulate the problem.
            //
            // What is the exact problem:
            // -> When executing a LINQ query that has a contains with only one element in the collection the same queryExpression string is generated by 2 different types
            //    of IQueryExpression, the 'NHibernate.Impl.ExpandedQueryExpression' and the 'NHibernate.Linq.NhLinqExpression' and that key is used to store a query plan
            //    in the QueryPlanCache if a query plan is requested and not found in the cache.
            // -> The 'NHibernate.Linq.NhLinqExpression' is typically added during the DefaultQueryProvider.PrepareQuery and the 'NHibernate.Impl.ExpandedQueryExpression'
            //    less likely during the execution of the LINQ query
            // -> Unfortunately the PrepareQuery is casting the returned query plan's QueryExpression to a NhLinqExpression, which it assumes will always be the case, but this
            //    is not true in a heavy loaded environment where the cache entries are constantly moving when other queries are being executed at the same time.
            // -> If you look at the following method inside the DefaultQueryProvider class, then you'll see that by drilling down in the PrepareQuery and in the ExecuteQuery, that
            //    both operations are actually requesting the query plan from the QueryPlanCache at some point
            //    public virtual object Execute(Expression expression)
            //    {
            //      IQuery query;
            //      NhLinqExpression nhQuery;
            //      NhLinqExpression nhLinqExpression = PrepareQuery(expression, out query, out nhQuery);
            //      return ExecuteQuery(nhLinqExpression, query, nhQuery);
            //    }
            //
            //    When they are requesting the corresponding query plan according to the QueryExpression's key the PrepareQuery assumes it will get back a NhLinqExpression, while it
            //    is perfectly possible that the corresponding query plan has a QueryExpression of type ExpandedQueryExpression that has been added during the ExecuteQuery because
            //    when a request was made for the query plan during the execution, the load on the cache has put the query plan with a QueryExpression of type NhLinqExpression and with
            //    the same key somewhere at the bottom of the MRU cache and it might even have been removed from the cache, resulting in adding a query plan with a QueryExpression value
            //    of type ExpandedQueryExpression. When the same LINQ query is executed afterwards, it will go through the PrepareQuery again, assuming that what is returned is a
            //    NhLinqExpression, while in reality it is an ExpandedQueryExpression, resulting in a cast exception. This problem might even go away due to the same load, pushing out
            //    the cached query plan with a QueryExpression of ExpandedQueryExpression and have a NhLinqExpression added back again during the next Prepare.
            //
            //    So this test will simulate the pushing out by clearing the cache as long as the QueryExpression of the query plan is NhLinqExpression, once it is an ExpandedQueryExpression
            //    it will stop clearing the cache, and the exception will occur, resulting in a failure of the test.
            //    The test will pass once all LINQ expression are executed (1000 max) and no exception occured

            var cache = new SoftLimitMRUCache(1);

            var queryPlanCacheType = typeof(QueryPlanCache);

            // get the planCache field on the QueryPlanCache and overwrite it with the restricted cache
            queryPlanCacheType
            .GetField("planCache", BindingFlags.Instance | BindingFlags.NonPublic)
            .SetValue(sessions.QueryPlanCache, cache);

            // Initiate a LINQ query with a contains with one item in it, of which we know that the underlying IQueryExpression implementations
            // aka NhLinqExpression and the ExpandedQueryExpression generate the same key.
            IEnumerable <int> personIds = new List <int>
            {
                1
            };

            ISession session = null;

            try
            {
                session = OpenSession();

                var allLinqQueriesSucceeded = false;

                // Setup an action delegate that will be executed on a separate thread and that will execute the LINQ query above multiple times.
                // This will constantly interact with the cache (Once in the PrepareQuery method of the DefaultQueryProvider and once in the Execute)
                System.Action queryExecutor = () =>
                {
                    var sessionToUse = sessions.OpenSession();

                    try
                    {
                        for (var i = 0; i < 1000; i++)
                        {
                            (from person in session.Query <Person>()
                             where personIds.Contains(person.Id)
                             select person).ToList();
                        }

                        allLinqQueriesSucceeded = true;
                    }
                    finally
                    {
                        if (sessionToUse != null && sessionToUse.IsOpen)
                        {
                            sessionToUse.Close();
                        }
                    }
                };

                (from person in session.Query <Person>()
                 where personIds.Contains(person.Id)
                 select person).ToList();

                // the planCache now contains one item with a key of type HQLQueryPlanKey,
                // so we are going to retrieve the generated key so that we can use it afterwards to interact with the cache.
                // The softReferenceCache field value from the SoftLimitMRUCache cache instance contains this key
                var field = cache.GetType().GetField("softReferenceCache", BindingFlags.NonPublic | BindingFlags.Instance);

                var softReferenceCache = (IEnumerable)field.GetValue(cache);

                // Since the cache only contains one item, the first one will be our key
                var queryPlanCacheKey = ((DictionaryEntry)softReferenceCache.First()).Key;

                // Setup an action that will be run on another thread and that will do nothing more than clearing the cache as long
                // as the value stored behind the cachekey is not of type ExpandedQueryExpression, which triggers the error.
                // By running this constantly in concurrency with the thread executing the query, the odds of having the wrong
                // QueryExpression in the cache (wrong as in the PrepareQuery is not expecting it) augments, simulating the workings
                // of the MRU algorithm under load.
                System.Action cacheCleaner = () =>
                {
                    while (!allLinqQueriesSucceeded)
                    {
                        var hqlExpressionQueryPlan = (QueryExpressionPlan)cache[queryPlanCacheKey];
                        if (hqlExpressionQueryPlan != null)
                        {
                            if (hqlExpressionQueryPlan.QueryExpression.GetType().FullName.Contains("NHibernate.Impl.ExpandedQueryExpression"))
                            {
                                // we'll stop clearing the cache, since the cache now has a different query expression type than expected by the code
                                break;
                            }
                        }

                        cache.Clear();

                        // we sleep a little, just to make sure the cache is not constantly empty ;-)
                        Thread.Sleep(50);
                    }
                };

                var queryExecutorAsyncResult = queryExecutor.BeginInvoke(null, null);
                var cacheCleanerAsyncResult  = cacheCleaner.BeginInvoke(null, null);

                queryExecutor.EndInvoke(queryExecutorAsyncResult);
                cacheCleaner.EndInvoke(cacheCleanerAsyncResult);

                Assert.IsTrue(allLinqQueriesSucceeded);
            }
            finally
            {
                if (session != null)
                {
                    session.Close();
                }
            }
        }
コード例 #48
0
 private void btnPause_Click(object sender, EventArgs e)
 {
     System.Action handler = new System.Action(this.pause); //定义委托
     handler.BeginInvoke(null, null);                       //异步调用
 }