Send() public method

public Send ( SendOrPostCallback d, object state ) : void
d SendOrPostCallback
state object
return void
Ejemplo n.º 1
1
        public void RunComparisonProcess(object param)
        {
            try
            {
                context = (SynchronizationContext)param;

                SetProgressPercentage(0);

                Logger.LogInfo("Starting comparison process...");

                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                EssayComparisonManager.Instance.IsComparisonCompete = false;
                EssayComparisonManager.Instance.EssayComparisonPercentage = Compare();

                stopwatch.Stop();

                var ts = stopwatch.Elapsed;
                var elapsedTime = string.Format("{0:00}:{1:00}:{2:00}.{3:000}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);

                Logger.LogInfo("Comparison completed. Elapsed time: " + elapsedTime);

                SetProgressPercentage(100);
                context.Send(OnWorkCompleted, elapsedTime);
            }
            catch (Exception ex)
            {
                Logger.LogError("Here is some problem..." + ex);
            }
        }
Ejemplo n.º 2
1
        public void RunReferrengProcess(object param)
        {
            try
            {
                context = (SynchronizationContext)param;
                UsePercentage = true;

                SetProgressPercentage(0);

                Logger.LogInfo("Starting referring process...");

                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                ReferringManager.Instance.IsReferringRunning = true;

                Logger.LogInfo("Getting sentence list.");
                sentenceList = ReferringManager.Instance.OriginalText.ClearUnnecessarySymbolsInText()
                    .DivideTextToSentences()
                    .ClearWhiteSpacesInList()
                    .RemoveEmptyItemsInList()
                    .ToLower();

                Logger.LogInfo("Getting word list.");
                wordList = ReferringManager.Instance.OriginalText.ClearUnnecessarySymbolsInText()
                    .DivideTextToWords()
                    .RemoveEmptyItemsInList()
                    .ToLower();

                Logger.LogInfo(string.Format("Text contains {0} sentences and {1} words.", sentenceList.Count, wordList.Count));

                Logger.LogInfo("Calculate word weights.");
                CalculateWordWeights();

                Logger.LogInfo("Calculating sentence weights.");
                CalculateSentenceWeights();

                Logger.LogInfo("Calculating required sentence count.");
                int sentenceCount = goodSentenceList.Count;
                int requiredSentenceCount = (int)(sentenceCount * ReferringManager.Instance.ReferringCoefficient);
                Logger.LogInfo(string.Format("Required sentences: {0}.", requiredSentenceCount));

                ReferringManager.Instance.OriginalTextSentenceCount = sentenceCount;
                ReferringManager.Instance.ReferredTextSentenceCount = requiredSentenceCount;

                Logger.LogInfo("Taking required sentences with biggest weight.");
                var requiredSentences = goodSentenceList.OrderByDescending(c => c.Weight).Take(requiredSentenceCount).ToList();

                Logger.LogInfo("Building the essay.");
                string essay = EssayBuilder.BuildEssay(requiredSentences, goodSentenceList);

                ReferringManager.Instance.ReferredText = essay;
                ReferringManager.Instance.IsReferringCompete = true;
                ReferringManager.Instance.OrderedWordList = goodWordList.TransformPOSToRussian().OrderByDescending(c => c.Weight).ToList();

                //order words and weights by weight only for comfortable view
                var showGoodWordList = ReferringManager.Instance.OrderedWordList;
                var showGoodSentenceList = goodSentenceList.OrderByDescending(c => c.Weight).ToList();

                stopwatch.Stop();

                var ts = stopwatch.Elapsed;
                var elapsedTime = string.Format("{0:00}:{1:00}:{2:00}.{3:000}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);

                Logger.LogInfo("Referring completed. Elapsed time: " + elapsedTime);

                SetProgressPercentage(100);
                context.Send(OnWorkCompleted, elapsedTime);
            }
            catch (Exception ex)
            {
                Logger.LogError("Here is some problem..." + ex);

                ReferringManager.Instance.IsReferringRunning = false;
            }
        }
Ejemplo n.º 3
0
        public RenderBuffer GetRender(string url, SynchronizationContext synchronizationContext)
        {
            WebView webView = null;
            synchronizationContext.Send((object state) => webView = WebCore.CreateWebView(1024, 768), null);

            synchronizationContext.Send(((object state) => webView.LoadURL(url)), null);

            while (webView.IsLoadingPage)
                SleepAndUpdateCore(synchronizationContext);

            webView.RequestScrollData();
            webView.ScrollDataReceived += OnScrollDataReceived;

            while (!_finishedScrollDataReceived)
                SleepAndUpdateCore(synchronizationContext);

            var width = _scrollData.ContentWidth > MaxWidth ? MaxWidth : _scrollData.ContentWidth;
            var height = _scrollData.ContentHeight > MaxHeight ? MaxHeight : _scrollData.ContentHeight;
            webView.Resize(width, height);

            while (webView.IsResizing)
                SleepAndUpdateCore(synchronizationContext);

            return webView.Render();
        }
        public void Work(System.Threading.SynchronizationContext synchronizationContext)
        {
            for (var i = 0; i < 100; i++)
            {
                if (_cancelled)
                {
                    break;
                }
                Thread.Sleep(50);                                     //some work

                synchronizationContext.Send(OnProgressChanged, i);    //swith method calling to main thread
            }
            synchronizationContext.Send(OnWorkCompleted, _cancelled); //switch method calling to main thread
        }
Ejemplo n.º 5
0
 private void Permitir()
 {
     Thread.Sleep(1000);
     mainThreadContext.Send(delegate
     {
         foreach (HtmlElement item in wb.Document.GetElementsByTagName("button"))
         {
             if (item.OuterHtml.Contains("auth-button button-primary"))
             {
                 item.InvokeMember("Click");
                 break;
             }
         }
     }, null);
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Retrieves the ably service time
        /// </summary>
        /// <returns></returns>
        public void Time(Action <DateTimeOffset?, AblyException> callback)
        {
            System.Threading.SynchronizationContext sync = System.Threading.SynchronizationContext.Current;

            Action <DateTimeOffset?, AblyException> invokeCallback = (res, err) =>
            {
                if (callback != null)
                {
                    if (sync != null)
                    {
                        sync.Send(new SendOrPostCallback(o => callback(res, err)), null);
                    }
                    else
                    {
                        callback(res, err);
                    }
                }
            };

            ThreadPool.QueueUserWorkItem(state =>
            {
                DateTimeOffset result;
                try
                {
                    result = _simpleRest.Time();
                }
                catch (AblyException e)
                {
                    invokeCallback(null, e);
                    return;
                }
                invokeCallback(result, null);
            });
        }
Ejemplo n.º 7
0
		public KinectReplay(string fileName)
		{
            Started = false;
			stream = File.OpenRead(fileName);
			reader = new BinaryReader(stream);

			synchronizationContext = SynchronizationContext.Current;

			Options = (KinectRecordOptions)reader.ReadInt32();
            //var paramsArrayLength = reader.ReadInt32();
            //var colorToDepthRelationalParameters = reader.ReadBytes(paramsArrayLength);
            //CoordinateMapper = new CoordinateMapper(colorToDepthRelationalParameters);

			if ((Options & KinectRecordOptions.Frames) != 0)
			{
				framesReplay = new ReplayAllFramesSystem();
				framesReplay.AddFrames(reader);
				framesReplay.ReplayFinished += () => synchronizationContext.Send(state => ReplayFinished.Raise(),null);
			}
			if ((Options & KinectRecordOptions.Audio) != 0)
			{
				var audioFilePath = Path.ChangeExtension(fileName, ".wav");
				if (File.Exists(audioFilePath))
					AudioFilePath = audioFilePath;
			}
            
		}
Ejemplo n.º 8
0
 /// <summary>
 /// Entry point of the application.
 /// </summary>
 /// <param name="args">An array of command line arguments.</param>
 public static void Main(string[] args)
 {
     try {
         var context = new SynchronizationContext();
         context.Send((x) => TaskMain().Wait(), null);
     } catch (AggregateException E) {
         throw E.InnerException;
     }
 }
        public CloverExamplePOSForm()
        {
            InitializeComponent();
            uiThread = WindowsFormsSynchronizationContext.Current;

            uiThread.Send(delegate (object state)
            {
                new StartupForm(this).Show();
            }, null);
        }
Ejemplo n.º 10
0
 internal static void SetTrayVisibleIndeterminent(this Page containerPage, String message, SynchronizationContext syncContext)
 {
     syncContext.Send(callback =>
     {
         SystemTray.SetIsVisible(containerPage, true);
         SystemTray.SetOpacity(containerPage, 0.5);
         var indicator = new ProgressIndicator {Text = message, IsVisible = true, IsIndeterminate = true};
         SystemTray.SetProgressIndicator(containerPage, indicator);
     }, null);
 }
		private static void DoFlash(IVectorGraphic graphic, SynchronizationContext context)
		{
			context.Send(delegate
			             	{
			             		if (graphic.ImageViewer != null && graphic.ImageViewer.DesktopWindow != null)
			             		{
			             			graphic.Color = _invalidColor;
			             			graphic.Draw();
			             		}
			             	}, null);
			Thread.Sleep(_flashDelay);
			context.Send(delegate
			             	{
			             		if (graphic.ImageViewer != null && graphic.ImageViewer.DesktopWindow != null)
			             		{
			             			graphic.Color = _normalColor;
			             			graphic.Draw();
			             		}
			             	}, null);
		}
        public DisposeWithViewModelTestControl()
        {
            InitializeComponent();
            syncContext = SynchronizationContext.Current;

            placeholder.Disposed += delegate
                                        {
                                            syncContext.Send(state => UpdateText(), null);
                                        };
            UpdateText();
        }
Ejemplo n.º 13
0
        //private void actualizarMarkersEnMapa(Dictionary<string, Zone.GeoCoord> markers, Dictionary<string,string> lstBubbles)
        private void actualizarMarkersEnMapa(Dictionary <string, Zone.GeoCoord> markers)
        {
            string coordArray = "";

            //string bubbleArray = "";

            foreach (KeyValuePair <string, Zone.GeoCoord> par in markers)
            {
                coordArray = coordArray + par.Key + "," + par.Value.latitude + "," + par.Value.longitude + ",";
                //coordArray = coordArray + par.Value.latitude + "," + par.Value.longitude + ",";
                //bubbleArray = bubbleArray + lstBubbles[par.Key].Replace("|"," ") + "|";
                if (ultimasPosGPS.ContainsKey(par.Key))
                {
                    ultimasPosGPS[par.Key] = par.Value.latitude + "," + par.Value.longitude;
                }
                else
                {
                    ultimasPosGPS.Add(par.Key, par.Value.latitude + "," + par.Value.longitude);
                }
            }
            coordArray = coordArray.TrimEnd(',');
            //bubbleArray = bubbleArray.TrimEnd('|');

            //object[] args = { coordArray,bubbleArray };
            object[] args = { coordArray };

            //Helpers.GetInstance().DoLog("Llama a verMarkers. coordarray: " + coordArray + " bubbleArray = " + bubbleArray);
            //Tools.GetInstance().DoLog("Llama a verMarkers. coordarray: " + coordArray );

            try
            {
                // Si no se llama asi, no se tiene acceso al webbrowser1
                mainThreadContext.Send(delegate
                {
                    webBrowser.Document.InvokeScript("verMarkers2", args);
                }, null);
            }
            catch (Exception) {  }
        }
Ejemplo n.º 14
0
 internal static async Task FlowController(this FrameworkElement fx, IEnumerable<Movie> movies, SynchronizationContext syncContext)
 {
     while (true)
     {
         await Task.Delay(TimeSpan.FromSeconds(Rand(7, 12))).ContinueWith(task => syncContext.Send(callback =>
         {
             var storyBd = fx.FindName("Update") as Storyboard;
             if (storyBd != null)
                 storyBd.Begin();
             fx.DataContext = movies.Shuffle();
         }, null));
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        /// 初始化音频
        /// </summary>
        void InitMedia()
        {
            _ticketMediaCheckTimer          = new Timer();
            _ticketMediaCheckTimer.Interval = 100;

            _ticketMediaCheckTimer.Tick += (s, e) =>
            {
                if (_checkTicketPromptMusic && !TicketPromptMusic.IsPlaying)
                {
                    _checkTicketPromptMusic = false;
                    _context.Send(OnMusicPlayStoped);
                }
                if (_checkTicketSuccessMusic && !TicketSuccessMusic.IsPlaying)
                {
                    _checkTicketSuccessMusic = false;
                    _context.Send(OnMusic4SuccessStop);
                }

                if (!_checkTicketSuccessMusic && !_checkTicketPromptMusic)
                {
                    _ticketMediaCheckTimer.Enabled = false;
                }
            };
        }
        private void QuerySurroundStationFromStationDB(PlaceFreqPlan[] freqs)
        {
            StationItemsSource.Clear();
            ActivityStationItemsSource.Clear();
            this.busyIndicator.IsBusy = true;
            EventWaitHandle[] waitHandles = new EventWaitHandle[freqs.Length];
            for (int i = 0; i < freqs.Length; i++)
            {
                waitHandles[i] = new AutoResetEvent(false);
            }
            System.Threading.SynchronizationContext     syccontext = System.Threading.SynchronizationContext.Current;
            Action <PlaceFreqPlan[], EventWaitHandle[]> action     = new Action <PlaceFreqPlan[], EventWaitHandle[]>(this.QuerySurroundStation);

            action.BeginInvoke(freqs, waitHandles, obj =>
            {
                WaitHandle.WaitAll(waitHandles);
                syccontext.Send(objs =>
                {
                    this.busyIndicator.IsBusy = false;

                    CreateSurroundStation(StationItemsSource);
                    if (ActivityStationItemsSource.Count > 0)
                    {
                        SurroundStationSelectorDialog stationdialog = new SurroundStationSelectorDialog(ActivityStationItemsSource);
                        stationdialog.SaveCallbcak += (result) =>
                        {
                            if (result)
                            {
                                this.Close();

                                if (RefreshItemsSource != null)
                                {
                                    RefreshItemsSource();
                                }
                            }
                        };
                        stationdialog.ShowDialog();
                    }
                    else
                    {
                        MessageBox.Show("未查询到周围台站,请重新选择查询条件");
                    }
                }, null);
            }, null);
        }
Ejemplo n.º 17
0
        public static void AddNotificationsSource(WordList list)
        {
            // REDO: for multiple sources of notifications
            wordList = list;

            if (notificationsTimer == null)
            {
                notificationsTimer = new System.Timers.Timer();
                notificationsTimer.Interval = 6000; //1000*60;
                notificationsTimer.AutoReset = false;
                notificationsTimer.Elapsed += notificationsTimer_Elapsed;
                notificationsTimer.Start();

                uiContext = SynchronizationContext.Current;

                uiContext.Send(ShowNotification, "test");
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Создает экземпляр сервиса для функционирования UDP hole punching. Без логирования.
        /// </summary>
        public P2PService(int port, bool usingIPv6)
        {
            disposed = false;
              requests = new List<RequestPair>();
              clientsEndPoints = new Dictionary<string, ClientDescription>();
              connectingClients = new HashSet<string>();

              NetPeerConfiguration config = new NetPeerConfiguration(AsyncPeer.NetConfigString);
              config.MaximumConnections = 100;
              config.Port = port;

              if (usingIPv6)
            config.LocalAddress = IPAddress.IPv6Any;

              syncContext = new EngineSyncContext();

              server = new NetServer(config);
              syncContext.Send(s => ((NetServer)s).RegisterReceivedCallback(ReceivedCallback), server);
              server.Start();
        }
Ejemplo n.º 19
0
        public void Start()
        {
            context = SynchronizationContext.Current;

            CancellationToken token = cancellationTokenSource.Token;

            Task.Factory.StartNew(() =>
            {
                foreach (ReplaySkeletonFrame frame in frames)
                {
                    Thread.Sleep(TimeSpan.FromMilliseconds(frame.TimeStamp));

                    if (token.IsCancellationRequested)
                        return;

                    ReplaySkeletonFrame closure = frame;
                    context.Send(state =>
                                    {
                                        if (SkeletonFrameReady != null)
                                            SkeletonFrameReady(this, new ReplaySkeletonFrameReadyEventArgs {SkeletonFrame = closure});
                                    }, null);
                }
            }, token);
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Allows performing the given func synchronously on the thread the dispatcher is associated with.
 /// </summary>
 /// <param name="syncContext">The synchronization object.</param>
 /// <param name="action">The func (function) to call.</param>
 public static void SynchronizeCall(SynchronizationContext syncContext, Action action)
 {
     syncContext.Send((o) => action(), null);
 }
Ejemplo n.º 21
0
 /// <summary>
 /// Faire Progresser le ProgressBar
 /// </summary>
 /// <param name="currentIndex"></param>
 /// <param name="maxRecords"></param>
 private static void ReportProgress(CssOptimizerModel model, SynchronizationContext current, int maxRecords)
 {
     if (current != null)
     current.Send((x) =>
     {
       model.ProgessBarEtat += Convert.ToInt32((1 / (decimal)maxRecords) * 100);
     }, null);
 }
Ejemplo n.º 22
0
        /// <summary>
        /// MAJ List Css File
        /// </summary>heni82
        /// <param name="model"></param>
        /// <param name="current">SynchronizationContext</param>
        /// <param name="filePath"></param>
        private static void MAJListCssFile(CssOptimizerModel model, SynchronizationContext current, string filePath)
        {
            if (current != null)
            current.Send((x) =>
            {
              if (model.ListCssFiles == null)
            model.ListCssFiles = new ObservableCollection<FileInformation>();

              model.ListCssFiles.Add(new FileInformation { Name = filePath.Split('/').Last() });
            }, null);
              else
              {
            if (model.ListCssFiles == null)
              model.ListCssFiles = new ObservableCollection<FileInformation>();

            model.ListCssFiles.Add(new FileInformation { Name = filePath.Split('/').Last() });
              }
        }
Ejemplo n.º 23
0
 private void SleepAndUpdateCore(SynchronizationContext synchronizationContext)
 {
     Thread.Sleep(100);
     synchronizationContext.Send((object state) => WebCore.Update(), null);
 }
 public void Send(SendOrPostCallback sendOrPostCallback, object state)
 {
     synchronizationContext.Send(sendOrPostCallback, state);
 }
Ejemplo n.º 25
0
        private IPlatformUser AuthenticateWithSso(SynchronizationContext context)
        {
            if (_ssoManager.ShouldUseSSOAuthentication())
            {
                var dialog = _sso.ResolveLoginDialog();
                dialog.SSODomainName = _ssoManager.GetSSODomainName();

                context.Send(delegate
                             {
                                 if (dialog.ShowDialog(IntPtr.Zero) == true)
                                 {
                                     User.DeviceToken = dialog.DeviceCredentialsCookie;
                                 }

                             }, null);

                return AuthenticateWithDeviceToken();
            }
            return null;
        }
Ejemplo n.º 26
0
        static void __InitPreviewForByteArrays(
            List<ByteArrayAndDrawable> list,
            CancellationToken ct,
            SynchronizationContext sync,
            Android.Content.Res.Resources res,
            Action callback)
        {
            for (int i = 0; i < list.Count && !ct.IsCancellationRequested; i++)
            {
                var bad = list[i];

                bad.drawable = GetResized(BitmapFactory.DecodeByteArray(bad.array, 0, bad.array.Length), res);

                list[i] = bad;

                if (!ct.IsCancellationRequested && callback != null && sync != null)
                    sync.Send(new SendOrPostCallback(state => callback()), null);
            }
        }
Ejemplo n.º 27
0
        public void GetMember(SynchronizationContext context)
        {
            try
            {
                _member = MainWindow.Bot.ParseMember(this.MemberId, this.Mode, this.Page);
                this.UserName = _member.UserName;

                ImageLoader.LoadImage(_member.AvatarUrl, _member.MemberUrl,
                            new Action<BitmapImage, string>((image, status) =>
                            {
                                this.AvatarImage = null;
                                this.AvatarImage = image;
                                _avatarImageStatus = status;
                            }
                        ));

                if (_member.Images != null)
                {
                    Images = new ObservableCollection<NijieImageViewModel>();
                    foreach (var image in _member.Images)
                    {
                        var temp = new NijieImageViewModel(image);
                        context.Send((x) =>
                        {
                            Images.Add(temp);
                        }, null);
                    }

                    this.Status = String.Format("Loaded: {0} images.", _member.Images.Count);
                    onPropertyChanged("TotalImages");
                    this.HasError = false;
                }
            }
            catch (NijieException ne)
            {
                MainWindow.Log.Error(ne.Message, ne);

                this.UserName = null;
                this.AvatarImage = ViewModelHelper.NoAvatar;
                context.Send((x) =>
                    {
                        if (Images != null)
                        {
                            Images.Clear();
                            Images = null;
                        }
                    }, null);

                this.HasError = true;
                this.Status = "[Error] " + ne.Message;
            }
        }
Ejemplo n.º 28
0
        private void buttonAdd_Click(object sender, RoutedEventArgs e)
        {
            var placeInfo = this.DataContext as ActivityPlaceInfo;

            if (placeInfo == null)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(placeInfo.Graphics))
            {
                MessageBox.Show("选择区域没有绘制范围,请先绘制区域范围");
                return;
            }
            var freqPlanList = this.dataGridFreqRange.ItemsSource as IList <PlaceFreqPlan>;

            if (freqPlanList == null)
            {
                return;
            }
            if (this.freqRanges == null)
            {
                this.freqRanges = CO_IA.Client.Utility.GetEquipmentClassFreqRanges();
            }
            string[] freqRangeGuids = (from data in freqPlanList select data.Key).ToArray();

            EquipmentClassFreqPlanningSelectWindow wnd = new EquipmentClassFreqPlanningSelectWindow();
            var selectableFreqRanges = from data in this.freqRanges where !freqRangeGuids.Contains(data.Key) select data;

            wnd.DataContext = selectableFreqRanges;
            if (wnd.ShowDialog(this) == true)
            {
                var checkedFreqRanges = wnd.GetCheckedFreqPlans();
                if (checkedFreqRanges.Length > 0)
                {
                    var calculateDistances = (from data in checkedFreqRanges where !this.dicDistanceRangPoints.ContainsKey(data.mDistanceToActivityPlace) select data.mDistanceToActivityPlace).Distinct().ToArray();

                    if (calculateDistances.Length > 0)
                    {
                        this.Busy("正在计算周围台站查询区域");
                        System.Threading.SynchronizationContext syncContext = System.Threading.SynchronizationContext.Current;
                        EventWaitHandle[] waitHandles = new EventWaitHandle[calculateDistances.Length];
                        for (int i = 0; i < waitHandles.Length; i++)
                        {
                            waitHandles[i] = new AutoResetEvent(false);
                        }
                        Action <int[], ActivityPlaceInfo, EventWaitHandle[]> action = new Action <int[], ActivityPlaceInfo, EventWaitHandle[]>(this.CalculateExtendPolygon);
                        action.BeginInvoke(calculateDistances, placeInfo, waitHandles, obj =>
                        {
                            var handles = obj.AsyncState as WaitHandle[];
                            WaitHandle.WaitAll(handles);
                            syncContext.Send(arg =>
                            {
                                this.Idle();
                                this.AddPlaceFreqPlans(checkedFreqRanges, placeInfo);
                            }, null);
                        }, waitHandles);
                    }
                    else
                    {
                        this.AddPlaceFreqPlans(checkedFreqRanges, placeInfo);
                    }
                }
            }
        }
        public void GetMyMemberBookmark(SynchronizationContext context)
        {
            try
            {
                var result = MainWindow.Bot.ParseMyMemberBookmark(this.Page);

                this.Members = new ObservableCollection<NijieMemberViewModel>();
                foreach (var item in result.Item1)
                {
                    NijieMemberViewModel m = new NijieMemberViewModel(item);
                    context.Send((x) =>
                    {
                        this.Members.Add(m);
                    }, null);
                }
                this.IsNextPageAvailable = result.Item2;
                this.Status = String.Format("Found {0} member(s).", this.Members.Count);
            }
            catch (NijieException ne)
            {
                this.Status = "Error: " + ne.Message;
            }
        }
Ejemplo n.º 30
0
        private void buttonStart_Click(object sender, EventArgs e)
        {
            Program.Run              = true;
            this.TopMost             = true;
            this.buttonStop.Enabled  = true;
            this.buttonStart.Enabled = false;
            string    stockName = "";
            Stopwatch sw        = new Stopwatch();
            var       path      = AppDomain.CurrentDomain.BaseDirectory;

            synchronizationContext = SynchronizationContext.Current;
            //FileStream fs = new FileStream(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Data_{DateTime.Now:yyyyMMdd}.txt"), FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
            //StreamReader sr = new StreamReader (fs,Encoding.Default);
            StreamWriter writer1 = new StreamWriter(_file);
            double       MaxTs   = 0;

            Task.Run(() =>
            {
                while (Program.Run)
                {
                    sw.Start();
                    string v0 = "", v1 = "", v2 = "";
                    Bitmap p0 = new Bitmap(10, 10), p1 = new Bitmap(10, 10), p2 = new Bitmap(10, 10);
                    var bmp   = Program.CoreAnalysis.Screenshot(out stockName);
                    var bmp0  = DeepCopyBitmap(bmp);
                    var bmp1  = DeepCopyBitmap(bmp);
                    var bmp2  = DeepCopyBitmap(bmp);
                    var x     = Program.CoreAnalysis.MarketList.SH.Contains(stockName) ? 3 : 0;
                    Parallel.Invoke(
                        () => {
                        if (radioButton0Local.Checked)
                        {
                            v0 = Program.CoreAnalysis.CatImageAnalysis(bmp0, 0 + x, out p0);
                        }
                        else
                        {
                            v0 = Program.CoreAnalysis.CatImageAnalysis2(bmp0, 0 + x, out p0);
                        }
                    }
                        ,
                        () =>
                    {
                        if (radioButton1Local.Checked)
                        {
                            v1 = Program.CoreAnalysis.CatImageAnalysis(bmp1, 1 + x, out p1);
                        }
                        else
                        {
                            v1 = Program.CoreAnalysis.CatImageAnalysis2(bmp1, 1 + x, out p1);
                        }
                    },
                        () =>
                    {
                        if (radioButton2Local.Checked)
                        {
                            v2 = Program.CoreAnalysis.CatImageAnalysis(bmp2, 2 + x, out p2);
                        }
                        else
                        {
                            v2 = Program.CoreAnalysis.CatImageAnalysis2(bmp2, 2 + x, out p2);
                        }
                    }

                        );
                    //if (radioButton0Local.Checked)
                    //{
                    //    v0 = Program.CoreAnalysis.CatImageAnalysis(bmp, 0, out p0);
                    //}
                    //else
                    //{
                    //    v0 = Program.CoreAnalysis.CatImageAnalysis2(bmp, 0, out p0);
                    //}
                    //if (radioButton1Local.Checked)
                    //{
                    //    v1 = Program.CoreAnalysis.CatImageAnalysis(bmp, 1, out p1);
                    //}
                    //else
                    //{
                    //    v1 = Program.CoreAnalysis.CatImageAnalysis2(bmp, 1, out p1);
                    //}
                    //if (radioButton2Local.Checked)
                    //{
                    //    v2 = Program.CoreAnalysis.CatImageAnalysis(bmp, 2, out p2);
                    //}
                    //else
                    //{
                    //    v2 = Program.CoreAnalysis.CatImageAnalysis2(bmp, 2, out p2);
                    //}

                    synchronizationContext.Send(a =>
                    {
                        this.label0.Text       = v0;
                        this.label1.Text       = v1;
                        this.label2.Text       = v2;
                        this.pictureBox0.Image = p0;
                        this.pictureBox1.Image = p1;
                        this.pictureBox2.Image = p2;
                    }, null);


                    sw.Stop();
                    TimeSpan ts = sw.Elapsed;


                    synchronizationContext.Send(a =>
                    {
                        label7.Text = "花费时间:" + ts.TotalMilliseconds;
                        if (ts.TotalMilliseconds > MaxTs)

                        {
                            MaxTs       = ts.TotalMilliseconds;
                            label8.Text = "最高花费时间:" + MaxTs.ToString();
                        }
                        this.Text = stockName;
                        writer1.WriteLine("{0:yyyy-MM-dd HH:mm:ss},股票:{1},买一价:{2},买1量:{3},买一笔数:{4}", DateTime.Now, stockName, v0, v1, v2);
                        writer1.Flush();
                    }, null);
                    Thread.Sleep(1000);
                    sw.Restart();
                }
            });
        }
Ejemplo n.º 31
0
        static void __InitPreviewForUris(
            List<PathAndDrawable> list,
            CancellationToken ct,
            SynchronizationContext sync,
            Android.Content.Res.Resources res,
            Action callback)
        {
            for (int i = 0; i < list.Count && !ct.IsCancellationRequested; i++)
            {
                var uad = list[i];

                if (uad.path.IsImage())
                {
                    try
                    {
                        uad.drawable = GetResized(Drawable.CreateFromPath(uad.path), res);
                    }
                    catch (Exception ex)
                    {
                        ex.Handle(true);
                    }
                }

                list[i] = uad;

                if (!ct.IsCancellationRequested && callback != null && sync != null)
                    sync.Send(new SendOrPostCallback(state => callback()), null);
            }
        }
Ejemplo n.º 32
0
        public void DoSearch(SynchronizationContext context)
        {
            NijieSearchOption option = new NijieSearchOption();
            option.Sort = Sort;
            option.Query = Query;
            option.Page = Page;
            option.SearchBy = SearchBy;
            option.Matching = Matching;

            try
            {
                _search = MainWindow.Bot.Search(option);

                Images = new ObservableCollection<NijieImageViewModel>();
                foreach (var image in _search.Images)
                {
                    var temp = new NijieImageViewModel(image);
                    context.Send((x) =>
                    {
                        Images.Add(temp);
                    }, null);
                }

                onPropertyChanged("TotalImages");
            }
            catch (NijieException ne)
            {
                Status = "Error: " + ne.Message;
            }
        }
Ejemplo n.º 33
0
 internal static Task SetTrayCollapsed(this Page containerPage, SynchronizationContext syncContext)
 {
     Thread.Sleep(2000);
     syncContext.Send(callback => SystemTray.SetIsVisible(containerPage, false), null);
     return null;
 }
 private static void DeliverViaSynchronizationContext(MethodInfo method, SynchronizationContext context, object target, object sender, object args)
 {
     if (context != null)
     {
         context.Send(delegate
         {
             DeliverMessage(method, target, sender, args);
         }, null);
     }
     else
     {
         DeliverMessage(method, target, sender, args);
     }
 }
Ejemplo n.º 35
0
 /// <summary>
 /// Entry point of the application.
 /// </summary>
 /// <param name="args">An array of command line arguments.</param>
 public static void Main(string[] args)
 {
     var context = new SynchronizationContext();
     context.Send((x) => AsyncMain().Wait(), null);
 }
Ejemplo n.º 36
0
        private IPlatformUser AuthenticateWithLoginDialog(SynchronizationContext context)
        {
            var dialog = new LoginForm(Host);
            var cancelled = false;
            context.Send(delegate
                         {
                             if (DialogResult.Cancel != dialog.ShowDialog())
                             {
                                 User.Email = dialog.LoginName;
                                 User.Password = dialog.LoginPassword;
                             }
                             else
                             {
                                 cancelled = true;
                             }
                         }, null);

            if (cancelled)
                throw new OperationCanceledException("Cancelled the login dialog.");

            return dialog.PlatformUser;
        }