Esempio n. 1
1
        public DiffViewer(TaskScheduler scheduler, HeapRecording instance)
            : base(scheduler)
        {
            InitializeComponent();

            ListFormat = new StringFormat {
                Trimming = StringTrimming.None,
                FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.FitBlackBox
            };

            Timeline.ItemValueGetter = GetBytesTotal;
            Timeline.ItemValueFormatter = MainWindow.FormatSizeBytes;

            Instance = instance;
            if (Instance != null) {
                Timeline.Items = Instance.Snapshots;
                Instance.TracebacksFiltered += Instance_TracebacksFiltered;
                ViewHistogramByModuleMenu.Enabled = ViewHistogramByFunctionMenu.Enabled = true;
                ViewHistogramBySourceFolderMenu.Enabled = ViewHistogramBySourceFileMenu.Enabled = true;
                ViewHistogramByNamespaceMenu.Enabled = ViewTreemapMenu.Enabled = true;
            } else {
                Timeline.Visible = false;
                MainSplit.Height += Timeline.Bottom - MainSplit.Bottom;
                ViewHistogramByModuleMenu.Enabled = ViewHistogramByFunctionMenu.Enabled = false;
                ViewHistogramBySourceFolderMenu.Enabled = ViewHistogramBySourceFileMenu.Enabled = false;
                ViewHistogramByNamespaceMenu.Enabled = ViewTreemapMenu.Enabled = false;
            }
        }
Esempio n. 2
0
        public ProcessWatcher(TaskScheduler scheduler, params string[] processNames)
        {
            Scheduler = scheduler;

            foreach (var pname in processNames) {
                var invariant = Path.GetFileNameWithoutExtension(pname).ToLowerInvariant();
                ProcessNames.Add(invariant);

                foreach (var process in Process.GetProcessesByName(invariant)) {
                    RunningProcessIds.Add(process.Id);
                    NewProcesses.Enqueue(process);
                }
            }

            try {
                var query = new WqlEventQuery(@"SELECT * FROM Win32_ProcessStartTrace");
                Watcher = new ManagementEventWatcher(query);
                Watcher.Options.BlockSize = 1;
                Watcher.EventArrived += new EventArrivedEventHandler(OnEventArrived);
                Watcher.Start();
                WatcherEnabled = true;
            } catch {
                Watcher = null;
                WatcherEnabled = false;

                TimerTask = Scheduler.Start(InitTimer(), TaskExecutionPolicy.RunAsBackgroundTask);
            }
        }
Esempio n. 3
0
        public void TestClonePipelining()
        {
            DoQuery("DROP TABLE IF EXISTS Test");
            DoQuery("CREATE TABLE Test (value int)");
            for (int i = 0; i < 10; i++)
                DoQuery(String.Format("INSERT INTO Test (value) VALUES ({0})", i));

            using (var scheduler = new TaskScheduler())
            using (var qm = new ConnectionWrapper(scheduler, Connection)) {
                var q = qm.BuildQuery("SELECT * FROM Test");
                var iter = q.Execute();
                var iterF = scheduler.Start(iter.Fetch());
                var fClone = qm.Clone();

                Assert.IsFalse(fClone.Completed);

                iter.Dispose();
                iterF.Dispose();
                scheduler.WaitFor(fClone);
                using (var dupe = fClone.Result) {
                    q = dupe.BuildQuery("SELECT COUNT(value) FROM Test WHERE value = ?");
                    var f = q.ExecuteScalar(5);
                    var result = scheduler.WaitFor(f);
                    Assert.AreEqual(result, 1);
                }
            }
        }
    public MyForm() {
        // Get a reference to a synchronization context task scheduler
        m_syncContextTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();

        Text = "Synchronization Context Task Scheduler Demo";
        Visible = true; Width = 600; Height = 100;
    }
        public void TaskScheduler_Shutdownで登録済みのタスクの終了待ちできる()
        {
            var scheduler = new TaskScheduler();
            var skipScheduler = new TaskScheduler();
            List<Task> tasks = new List<Task>();

            for (int i = 0; i < 100; i++)
            {
                var t = Util.RandomTask(scheduler, skipScheduler);
                tasks.Add(t);
                scheduler.Update();
                skipScheduler.Update();
            }

            // RandomTask と WaitShutdown の実装上、5秒も待てば終わるはず
            var s = scheduler.BeginShutdown(TimeSpan.FromSeconds(10));

            while (true)
            {
                if (s.IsFaulted || s.IsCompleted || s.IsCanceled) break;
                for (int i = 0; i < 50; i++) scheduler.Update();
                for (int i = 0; i < 5; i++) skipScheduler.Update();
                System.Threading.Thread.Sleep(1);
            }

            Assert.AreEqual(TaskSchedulerStatus.ShutdownCompleted, scheduler.Status);

            foreach (var t in tasks)
            {
                Assert.AreEqual(TaskStatus.RanToCompletion, t.Status);
            }
        }
Esempio n. 6
0
            public Registration () {
                Scope = CancellationScope.Current;
                Scheduler = TaskScheduler.Current;

                if (Scheduler == null)
                    throw new InvalidOperationException("No implicitly active TaskScheduler on this thread.");
            }
Esempio n. 7
0
        public void InsertBenchmark (int warmupLength, int numInsertions, Func<IJobQueue> jobQueueFactory, Func<ConnectionWrapper, Query, int, IEnumerator<object>> insertTask) {
            DoQuery("CREATE TABLE Test (A INTEGER NOT NULL, B INTEGER NOT NULL)");

            var jobQueue = jobQueueFactory();
            var wjq = jobQueue as WindowsMessageJobQueue;

            using (var scheduler = new TaskScheduler(() => jobQueue))
            using (var cw = new ConnectionWrapper(scheduler, Connection))
            using (var query = cw.BuildQuery("INSERT INTO Test (A, B) VALUES (?, ?)")) {
                scheduler.WaitFor(insertTask(cw, query, warmupLength));
                DoQuery("DELETE FROM Test");

                var e = insertTask(cw, query, numInsertions);
                long timeStart = Time.Ticks;

                scheduler.WaitFor(e);

                long elapsed = Time.Ticks - timeStart;
                var elapsedSeconds = (decimal)elapsed / Time.SecondInTicks;

                Console.WriteLine(
                    "Inserted {0} row(s) in {1:00.000} second(s) at ~{2:000000.00} rows/sec.",
                    numInsertions, elapsedSeconds, numInsertions / elapsedSeconds
                );
            }
        }
        public RunSettingTaskDetail(TaskScheduler task)
        {
            InitializeComponent();
            this.LayoutRoot.DataContext = task;

            this.ContentTextBox.Text = this.GetParameterSettings(task);
        }
Esempio n. 9
0
        public LogWindow(TaskScheduler scheduler)
            : base(scheduler)
        {
            InitializeComponent();

            GC.Collect();
        }
 void ISchedulable.Schedule(TaskScheduler scheduler, IFuture future)
 {
     _Future = future;
     _Scheduler = scheduler;
     _Future.RegisterOnDispose(this.OnDisposed);
     QueueStep();
 }
Esempio n. 11
0
        public void タスクの2重起動防止()
        {
            const int Frame = 30;
            const int N = 10;

            var scheduler = new TaskScheduler();

            Func<Task> starter = () => Util.DelayFrame(Frame, scheduler);
            var distinct = TaskUtility.Distinct(starter);

            Task task = distinct();

            for (int i = 0; i < (Frame + 1) * N; i++)
            {
                var t = distinct();

                if (task.IsCompleted)
                {
                    // タスク完了してたら次のタスクを起動してるはず。
                    Assert.IsFalse(object.ReferenceEquals(task, t));

                    task = t;
                }
                else
                {
                    // タスク完了するまでは同じタスクが何度も帰ってくるはず。
                    Assert.IsTrue(object.ReferenceEquals(task, t));
                }

                scheduler.Update();
            }
        }
Esempio n. 12
0
        public virtual void SetUp()
        {
            Scheduler = new TaskScheduler();

            TestFile = Path.GetTempFileName();
            Storage = new AlternateStreamSource(TestFile);
        }
Esempio n. 13
0
        public HttpServer(TaskScheduler scheduler)
        {
            EndPoints = new EndPointList(this);

            Scheduler = scheduler;

            RequestOnComplete = _RequestOnComplete;
        }
Esempio n. 14
0
 public frmSchedule(DataStorage data, TaskScheduler.ScheduledTasks tasks, DataStorage.JobRow job, bool newJob)
 {
     Localization.ChangeLanguage();
     InitializeComponent();
     m_Data = data;
     m_NewJob = newJob;
     m_Job = job;
     m_Tasks = tasks;
 }
        public void SetUp()
        {
            _tasks = CreateTasks();

            _timer = new Mock<ITimer>();
            _taskRunner = new Mock<ITaskRunner>();

            _taskScheduler = new TaskScheduler(_timer.Object, _taskRunner.Object);
        }
Esempio n. 16
0
        void Application_Start(object sender, EventArgs e)
        {
            XmlDocument xml = new XmlDocument();
            xml.Load(Server.MapPath(@"\config\tasks.config"));
            XmlNodeList nodes = xml.SelectNodes("Tasks/Task");

            this._scheduler = new TaskScheduler(nodes);
            this._scheduler.StartTasks();
        }
Esempio n. 17
0
 public SchedulerProvider()
 {
     Task = new TaskScheduler();
     IOCompletion = new IOCompletionScheduler();
     Current = new CurrentScheduler();
     Immediate = new ImmediateScheduler();
     NewThread = new NewThreadScheduler();
     ThreadPool = new ThreadPoolScheduler();
 }
Esempio n. 18
0
        void ISchedulable.Schedule(TaskScheduler scheduler, IFuture future)
        {
            if (future == null)
                throw new ArgumentNullException("future");

            _Future = future;
            _Scheduler = scheduler;
            _Future.RegisterOnDispose(this.OnDisposed);
            QueueStep();
        }
        private string GetParameterSettings(TaskScheduler task)
        {
            string parameterString = string.Empty;

            foreach (ParameterSettingTask setting in task.ParameterSettings)
            {
                parameterString += setting.ParameterKey + ":" + setting.ParameterValue;
            }
            return parameterString;
        }
        public void AddTaskScheduler(TaskScheduler taskScheduler)
        {
            var task = this._TaskSchedulers.Where(P => P.Id == taskScheduler.Id);
            if (taskScheduler.RunTime <= DateTime.Now) return;
            if (task.Count() == 0)
            {
                this._TaskSchedulers.Add(taskScheduler);
            }

            taskScheduler.ScheduleID = this.Scheduler.Add(this._UpdateSettingAction, taskScheduler, taskScheduler.RunTime);
        }
        public void DeleteTaskScheduler(TaskScheduler taskScheduler)
        {
            IEnumerable<TaskScheduler> task = this._TaskSchedulers.Where(P => P.Id == taskScheduler.Id);
            TaskScheduler taskSchedulerEntity = task.ToList()[0];
            if (taskScheduler.RunTime <= DateTime.Now) return;

            if (taskSchedulerEntity != null)
            {
                this.Scheduler.Remove(taskSchedulerEntity.ScheduleID);
            }
        }
        /// <summary>
        ///     Initialisiert eine neue Instanz der <see cref="CommonApplication" /> Klasse.
        /// </summary>
        /// <param name="doStartup">
        ///     The do startup.
        /// </param>
        /// <param name="service">
        ///     The service.
        /// </param>
        /// <param name="factory">
        ///     The factory.
        /// </param>
        protected CommonApplication(bool doStartup, [CanBeNull] ISplashService service, [NotNull] IUIControllerFactory factory)
        {
            Contract.Requires<ArgumentNullException>(factory != null, "factory");

            Factory = factory;
            Current = this;
            _scheduler = new TaskScheduler(UiSynchronize.Synchronize);
            _splash = service ?? new NullSplash();
            _doStartup = doStartup;
            SourceAssembly = new AssemblyName(Assembly.GetAssembly(GetType()).FullName).Name;
        }
Esempio n. 23
0
        public void タスクのタイムアウト()
        {
            const int N = 10;
            const int T1 = 50;
            const int T2 = 100;

            var scheduler = new TaskScheduler();

            // 50秒でタイムアウトのものを100秒放置して、タイムアウトさせる
            {
                var t = TaskUtility.RunWithTimeout(ct => Util.DelayFrame(N, ct, scheduler), TimeSpan.FromMilliseconds(T1));
                Thread.Sleep(T2);

                scheduler.Update(N + 1);

                Assert.IsTrue(t.IsFaulted);
                Assert.IsTrue(t.Exception.Exceptions.Any(x => x is TimeoutException));
            }

            // 100秒でタイムアウトのものを50秒放置後、ちゃんと完了させる
            {
                var t = TaskUtility.RunWithTimeout(ct => Util.DelayFrame(N, ct, scheduler), TimeSpan.FromMilliseconds(T2));
                Thread.Sleep(T1);

                scheduler.Update(N + 1);

                Assert.IsTrue(t.IsCompleted);
            }

            // 50秒でタイムアウトのものを100秒放置して、タイムアウトさせる
            {
                var t = TaskUtility.RunWithTimeout(ct => Util.Delay(T2, ct), TimeSpan.FromMilliseconds(T1));
                while (!t.IsCompleted)
                {
                    scheduler.Update();
                    Thread.Sleep(1);
                }

                Assert.IsTrue(t.IsFaulted);
            }

            // 100秒でタイムアウトのものを50秒放置後、ちゃんと完了させる
            {
                var t = TaskUtility.RunWithTimeout(ct => Util.Delay(T1, ct), TimeSpan.FromMilliseconds(T2));
                while (!t.IsCompleted)
                {
                    scheduler.Update();
                    Thread.Sleep(1);
                }

                Assert.IsTrue(t.IsCompleted);
            }
        }
Esempio n. 24
0
        public ServiceProvider(bool debugPayload)
        {
            Scheduler = new TaskScheduler(JobQueue.WindowsMessageBased);

            var assembly = Assembly.GetExecutingAssembly();
            using (var stream = assembly.GetManifestResourceStream(
                debugPayload ?
                    "XPTrace.payload_debug.dll" :
                    "XPTrace.payload.dll"
            ))
                Payload = new PortableExecutable(stream);
        }
        /// <summary>Initialies the ConcurrentExclusiveInterleave.</summary>
        /// <param name="targetScheduler">The target scheduler on which this interleave should execute.</param>
        /// <param name="exclusiveProcessingIncludesChildren">Whether the exclusive processing of a task should include all of its children as well.</param>
        public ConcurrentExclusiveInterleave(TaskScheduler targetScheduler, bool exclusiveProcessingIncludesChildren)
        {
            // A scheduler must be provided
            if (targetScheduler == null) throw new ArgumentNullException("targetScheduler");

            // Create the state for this interleave
            _internalLock = new object();
            _exclusiveProcessingIncludesChildren = exclusiveProcessingIncludesChildren;
            _parallelOptions = new ParallelOptions() { TaskScheduler = targetScheduler };
            _concurrentTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, new Queue<Task>(), targetScheduler.MaximumConcurrencyLevel);
            _exclusiveTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, new Queue<Task>(), 1);
        }
Esempio n. 26
0
        static void Main (string[] args) {
            Scheduler = new TaskScheduler();

            World.Create();
            Event.Broadcast(new { Type = EventType.WorldConstructed });

            Server = new TelnetServer(Scheduler, System.Net.IPAddress.Any, 23);
            Scheduler.Start(HandleNewClients(), TaskExecutionPolicy.RunAsBackgroundTask);

            while (true) {
                Scheduler.Step();
                Scheduler.WaitForWorkItems();
            }
        }
Esempio n. 27
0
        /// <summary>
        /// タイマーを使って、指定した遅延時間[ミリ秒]後に完了するタスクを作る。
        /// </summary>
        /// <param name="milliSecond">遅延時間</param>
        /// <returns></returns>
        public static Task Delay(int milliSecond, TaskScheduler scheduler)
        {
            var tcs = new TaskCompletionSource<object>(scheduler);

            Timer timer = null;

            timer = new Timer(_ =>
            {
                timer.Dispose();
                tcs.SetResult(null);
            }, null, milliSecond, Timeout.Infinite);

            return tcs.Task;
        }
Esempio n. 28
0
        public DatabaseFile(TaskScheduler scheduler, string filename)
            : this(scheduler)
        {
            _Filename = filename;
            if (File.Exists(_Filename))
                File.Delete(_Filename);

            Directory.CreateDirectory(_Filename);
            Storage = new FolderStreamSource(_Filename);

            MakeTokenFile(filename);

            Scheduler.Start(CreateTangles(), TaskExecutionPolicy.RunAsBackgroundTask);
        }
Esempio n. 29
0
        public MainWindow(TaskScheduler scheduler)
            : base(scheduler)
        {
            InitializeComponent();

            PersistedControls = new[] {
                BoundMember.New(() => ExecutablePath.Text),
                BoundMember.New(() => Arguments.Text),
                BoundMember.New(() => WorkingDirectory.Text)
            };

            SnapshotTimeline.ItemValueGetter = GetPagedMemory;
            SnapshotTimeline.ItemValueFormatter = FormatSizeBytes;

            LoadPersistedValues();
        }
        public void AddTaskScheduler(TaskScheduler taskScheduler)
        {
            try
            {
                TaskScheduler task = this.GetTaskScheduler(taskScheduler.Id);
                if (taskScheduler.RunTime <= DateTime.Now) return;

                switch (taskScheduler.ActionType)
                {
                    case ActionType.OneTime:
                        taskScheduler.ScheduleID = this.Scheduler.Add(this._UpdateSettingAction, taskScheduler, taskScheduler.RunTime);
                        break;
                    case ActionType.Daily:
                        taskScheduler.ScheduleID = this.Scheduler.Add(this._UpdateSettingAction, taskScheduler, taskScheduler.RunTime);
                        break;
                    case ActionType.Weekly:
                        DateTime startRunDate = taskScheduler.RunTime.Date;
                        TimeSpan startRunDiff = taskScheduler.RunTime - startRunDate;
                        string weekSN = taskScheduler.WeekDaySN;
                        int[] dayDiffs = TaskCheckManager.GetWeekTaskRunInterval(weekSN);

                        foreach (int dayDiff in dayDiffs)
                        {
                            DateTime runTaskTime = DateTime.Now + TimeSpan.FromDays(dayDiff) + startRunDiff;
                            string schedulerId = this.Scheduler.Add(this._UpdateSettingAction,taskScheduler, runTaskTime, DateTime.MaxValue, TimeSpan.FromDays(7));
                            taskScheduler.ScheduleIDs.Add(schedulerId);
                        }
                        break;
                    default:
                        taskScheduler.ScheduleID = this.Scheduler.Add(this._UpdateSettingAction, taskScheduler, taskScheduler.RunTime);
                        break;
                }

                if (task == null)
                {
                    this._TaskSchedulers.Add(taskScheduler);
                }
                else
                {
                    task.ScheduleID = taskScheduler.ScheduleID;
                }
            }
            catch (Exception ex)
            {
                Logger.TraceEvent(TraceEventType.Error, "SettingsTaskSchedulerManager.AddTaskScheduler\r\n{0}", ex.ToString());
            }
        }
Esempio n. 31
0
 internal static System.Threading.Tasks.Task StartNew(this TaskScheduler scheduler, Action func)
 {
     return(System.Threading.Tasks.Task.Factory.StartNew(func, default(CancellationToken), TaskCreationOptions.None, scheduler));
 }
Esempio n. 32
0
 /// <summary>
 /// Create a new Disruptor. Will default to <see cref="BlockingWaitStrategy"/> and <see cref="ProducerType.Multi"/>.
 /// </summary>
 /// <param name="eventFactory">the factory to create events in the ring buffer</param>
 /// <param name="ringBufferSize">the size of the ring buffer, must be power of 2</param>
 /// <param name="taskScheduler">a <see cref="TaskScheduler"/> to create threads for processors</param>
 public Disruptor(Func <T> eventFactory, int ringBufferSize, TaskScheduler taskScheduler)
     : this(RingBuffer <T> .CreateMultiProducer(eventFactory, ringBufferSize), new BasicExecutor(taskScheduler))
 {
 }
Esempio n. 33
0
 public Task ContinueWhenLoaded(Action <Task <ModuleDefinition> > onAssemblyLoaded, TaskScheduler taskScheduler)
 {
     return(this.assemblyTask.ContinueWith(onAssemblyLoaded, default(CancellationToken), TaskContinuationOptions.RunContinuationsAsynchronously, taskScheduler));
 }
Esempio n. 34
0
        private void AsyncListarAgenda(List <string> sqlcommand)
        {
            BlackBox      = Visibility.Visible;
            StartProgress = true;
            PrintBox      = Visibility.Collapsed;
            MainBox       = Visibility.Visible;

            Task.Factory.StartNew(() => mdata.AgendaCliente(sqlcommand))
            .ContinueWith(task =>
            {
                if (task.IsCompleted)
                {
                    ListarAgenda = task.Result;



                    BlackBox      = Visibility.Collapsed;
                    StartProgress = false;
                }
                else
                {
                    BlackBox      = Visibility.Collapsed;
                    StartProgress = false;
                }
            },
                          System.Threading.CancellationToken.None,
                          TaskContinuationOptions.None,
                          TaskScheduler.FromCurrentSynchronizationContext());

            Task <mPF_Ext> .Factory.StartNew(() => mdata.ExistPessoaFisica(new mMascaras().Remove(GetCNPJCPF)))
            .ContinueWith(task =>
            {
                if (task.IsCompleted)
                {
                    Cliente.Inscricao = task.Result.CPF;
                    Cliente.NomeRazao = task.Result.Nome;
                    Cliente.Telefones = task.Result.Telefones;
                    Cliente.Email     = task.Result.Email;


                    if (Cliente.Inscricao == string.Empty || Cliente.Inscricao == null)
                    {
                        Task <mPJ_Ext> .Factory.StartNew(() => mdata.ExistPessoaJuridica(new mMascaras().Remove(GetCNPJCPF)))
                        .ContinueWith(task2 =>
                        {
                            if (task2.IsCompleted)
                            {
                                Cliente.Inscricao = task2.Result.CNPJ;
                                Cliente.NomeRazao = task2.Result.RazaoSocial;
                                Cliente.Telefones = task2.Result.Telefones;
                                Cliente.Email     = task2.Result.Email;
                            }
                        },
                                      System.Threading.CancellationToken.None,
                                      TaskContinuationOptions.None,
                                      TaskScheduler.FromCurrentSynchronizationContext());
                    }
                }
            },
                          System.Threading.CancellationToken.None,
                          TaskContinuationOptions.None,
                          TaskScheduler.FromCurrentSynchronizationContext());
        }
Esempio n. 35
0
 private Task InvokeGrainAsync(TaskScheduler orleansTaskScheduler, Func <IBackgroundWorkload <TRequest, TResponse>, Task> action) =>
 Task.Factory.StartNew(async() =>
 {
     var grain = GrainFactory.GetGrain <IBackgroundWorkload <TRequest, TResponse> >(this.GetPrimaryKeyString());
     await action(grain);
 }, CancellationToken.None, TaskCreationOptions.None, orleansTaskScheduler);
Esempio n. 36
0
        bool ExecuteCommandInternal(string input)
        {
            Debug.Assert(execState != null && !execState.IsInitializing);
            if (execState == null || execState.IsInitializing)
            {
                return(true);
            }
            lock (lockObj) {
                Debug.Assert(execState.ExecTask == null && !execState.Executing);
                if (execState.ExecTask != null || execState.Executing)
                {
                    return(true);
                }
                execState.Executing = true;
            }

            try {
                var scState = ParseScriptCommand(input);
                if (scState != null)
                {
                    if (execState != null)
                    {
                        lock (lockObj)
                            execState.Executing = false;
                    }
                    scState.Command.Execute(this, scState.Arguments);
                    bool isReset = scState.Command is ResetCommand;
                    if (!isReset)
                    {
                        CommandExecuted();
                    }
                    return(true);
                }

                var oldState = execState;

                var taskSched = TaskScheduler.FromCurrentSynchronizationContext();
                Task.Run(() => {
                    AppCulture.InitializeCulture();
                    oldState.CancellationTokenSource.Token.ThrowIfCancellationRequested();

                    var opts     = oldState.ScriptOptions.WithReferences(Array.Empty <MetadataReference>()).WithImports(Array.Empty <string>());
                    var execTask = oldState.ScriptState.ContinueWithAsync(input, opts, oldState.CancellationTokenSource.Token);
                    oldState.CancellationTokenSource.Token.ThrowIfCancellationRequested();
                    lock (lockObj) {
                        if (oldState == execState)
                        {
                            oldState.ExecTask = execTask;
                        }
                    }
                    execTask.ContinueWith(t => {
                        var ex = t.Exception;
                        bool isActive;
                        lock (lockObj) {
                            isActive = oldState == execState;
                            if (isActive)
                            {
                                oldState.ExecTask = null;
                            }
                        }
                        if (isActive)
                        {
                            if (ex != null)
                            {
                                replEditor.OutputPrintLine(ex.ToString());
                            }

                            if (!t.IsCanceled && !t.IsFaulted)
                            {
                                oldState.ScriptState = t.Result;
                                var val = t.Result.ReturnValue;
                                if (val != null)
                                {
                                    replEditor.OutputPrintLine(Format(val));
                                }
                            }

                            CommandExecuted();
                        }
                    }, CancellationToken.None, TaskContinuationOptions.None, taskSched);
                })
                .ContinueWith(t => {
                    if (execState != null)
                    {
                        lock (lockObj)
                            execState.Executing = false;
                    }
                    var innerEx = t.Exception?.InnerException;
                    if (innerEx is CompilationErrorException)
                    {
                        var cee = (CompilationErrorException)innerEx;
                        PrintDiagnostics(cee.Diagnostics);
                        CommandExecuted();
                    }
                    else if (innerEx is OperationCanceledException)
                    {
                        CommandExecuted();
                    }
                    else
                    {
                        ReportException(t);
                    }
                }, CancellationToken.None, TaskContinuationOptions.None, taskSched);

                return(true);
            }
            catch (Exception ex) {
                if (execState != null)
                {
                    lock (lockObj)
                        execState.Executing = false;
                }
                replEditor.OutputPrintLine(string.Format("Error executing script:\n\n{0}", ex));
                return(false);
            }
        }
Esempio n. 37
0
        private void NewEmployeeSaveButton_Click(object sender, EventArgs e)
        {
            ArrayList Employee           = new ArrayList();
            string    EmployeeName       = NewEmployeeNameTextBox.Text;
            string    EmployeeAddress    = NewEmployeeAddressTextBok.Text;
            string    EmployeeEmail      = NewEmployeeEmailTextBox.Text;
            string    EmployeeID         = NewEmployeeIDTextBox.Text;
            string    EmployeePassword   = NewEmployeePasswordTextBox.Text;
            string    EmployeeRePassword = NewEmployeeRePasswordTextBox.Text;
            string    EmployeeUsername   = NewEmployeeUsernameTextBox.Text;
            string    EmployeeGender     = "";

            Boolean flag  = false;
            Boolean flag1 = false;


            if (MaleEmployee.Checked)
            {
                EmployeeGender = "Male";
            }
            if (FemaleEmployee.Checked)
            {
                EmployeeGender = "Female";
            }

            Boolean empty = string.IsNullOrEmpty(EmployeeName) || string.IsNullOrEmpty(EmployeeAddress) || string.IsNullOrEmpty(EmployeeEmail) || string.IsNullOrEmpty(EmployeeID) || string.IsNullOrEmpty(EmployeePassword) || string.IsNullOrEmpty(EmployeeRePassword) || string.IsNullOrEmpty(EmployeeUsername) || string.IsNullOrEmpty(EmployeeGender);



            string query = "select UserID  from Employee where UserID= '" + EmployeeID + "';";

            Connection.Open();
            Command = new SqlCommand(query, Connection);
            SqlDataReader result = Command.ExecuteReader();

            while (result.Read())
            {
                string id = result["UserID"].ToString();
                flag = true;
            }
            Connection.Close();
            string query1 = "select UserUsername  from Employee where UserUsername= '******';";

            Connection.Open();
            Command1 = new SqlCommand(query1, Connection);
            SqlDataReader result1 = Command1.ExecuteReader();


            while (result1.Read())
            {
                string name = result1["UserUsername"].ToString();
                flag1 = true;
            }

            Connection.Close();

            if (empty)
            {
                var w = new Form()
                {
                    Size = new Size(0, 0)
                };
                Task.Delay(TimeSpan.FromSeconds(1))
                .ContinueWith((t) => w.Close(), TaskScheduler.FromCurrentSynchronizationContext());
                MessageBox.Show(w, "Please fill all the fields");
            }
            else if (!EmployeePassword.Equals(EmployeeRePassword))
            {
                var w = new Form()
                {
                    Size = new Size(0, 0)
                };
                Task.Delay(TimeSpan.FromSeconds(1))
                .ContinueWith((t) => w.Close(), TaskScheduler.FromCurrentSynchronizationContext());
                MessageBox.Show(w, "Password not matched");
            }
            else if (flag)
            {
                var w = new Form()
                {
                    Size = new Size(0, 0)
                };
                Task.Delay(TimeSpan.FromSeconds(1))
                .ContinueWith((t) => w.Close(), TaskScheduler.FromCurrentSynchronizationContext());
                MessageBox.Show(w, "ID already exist");
            }
            else if (flag1)
            {
                var w = new Form()
                {
                    Size = new Size(0, 0)
                };
                Task.Delay(TimeSpan.FromSeconds(1))
                .ContinueWith((t) => w.Close(), TaskScheduler.FromCurrentSynchronizationContext());
                MessageBox.Show(w, "Username not available");
            }
            else
            {
                Employee.Add(EmployeeID);
                Employee.Add(EmployeeName);
                Employee.Add(EmployeeEmail);
                Employee.Add(EmployeeUsername);
                Employee.Add(EmployeeRePassword);
                Employee.Add(EmployeeGender);
                Employee.Add(EmployeeAddress);
                database.InsertNewEmployee(Employee);
                var w = new Form()
                {
                    Size = new Size(0, 0)
                };
                Task.Delay(TimeSpan.FromSeconds(2))
                .ContinueWith((t) => w.Close(), TaskScheduler.FromCurrentSynchronizationContext());
                MessageBox.Show(w, "Employee Added successfully");
            }

            EmployeeInformation eq = new EmployeeInformation();

            eq.LoadData();
        }
Esempio n. 38
0
 public static Task RunUI(TaskScheduler context, Action func)
 {
     return(Task.Factory.StartNew(func, new CancellationToken(), TaskCreationOptions.None, context));
 }
Esempio n. 39
0
        /// <summary>
        /// The main test method that execute the API. There are five steps involved in the execution of the test
        /// </summary>
        internal void RealRun()
        {
            TaskScheduler ts = TaskScheduler.Default;

            switch (_taskSchedulerType)
            {
            case TaskSchedulerType.Null:
                ts = null;
                break;

            case TaskSchedulerType.CustomWithInlineExecution:
                ts = new TaskRunSyncTaskScheduler(true);
                break;

            case TaskSchedulerType.CustomWithoutInlineExecution:
                ts = new TaskRunSyncTaskScheduler(false);
                break;

            default:
                ts = TaskScheduler.Default;
                break;
            }

            // Stage 1 -- create task
            CreateTask();

            // Stage 2 - start with the pre-action
            switch (_preTaskStatus)
            {
            case PreTaskStatus.Continued:
                _task = _task.ContinueWith((t) => { }, _cts.Token, TaskContinuationOptions.None, ts);
                break;

            case PreTaskStatus.Running:
                _task.Start(ts);
                break;

            case PreTaskStatus.Canceled:
                _cts.Cancel();
                break;

            case PreTaskStatus.Completed:
                _task.Start(ts);
                ((IAsyncResult)_task).AsyncWaitHandle.WaitOne();      // wait on AsyncWaitHandle to avoid getting exp
                break;
            }

            int expectedThreadID = Environment.CurrentManagedThreadId;

            // Stage 3 -  exercise the API
            try
            {
                if (_taskSchedulerType == TaskSchedulerType.Default)
                {
                    _task.RunSynchronously();
                }
                else
                {
                    _task.RunSynchronously(ts);
                }

                if (ExpectRunSyncFailure)
                {
                    Assert.True(false, string.Format("Fail to throw expected InvalidOperationException"));
                }
                if (_taskSchedulerType == TaskSchedulerType.Null)
                {
                    Assert.True(false, string.Format("Fail to throw expected ArgumentNullException"));
                }
            }
            catch (InvalidOperationException ex)
            {
                if (!ExpectRunSyncFailure)
                {
                    Assert.True(false, string.Format("Caught un-expected InvalidOperationException - {0}", ex));
                }
                else
                {
                    Debug.WriteLine("Caught expected InvalidOperationException");
                    DisposeScheduler(ts);
                    return;
                }
            }
            catch (ArgumentNullException ex)
            {
                if (_taskSchedulerType != TaskSchedulerType.Null)
                {
                    Assert.True(false, string.Format("Caught un-expected ArgumentNullException - {0}", ex));
                }
                else
                {
                    Debug.WriteLine("Caught expected ArgumentNullException");
                    DisposeScheduler(ts);
                    return;
                }
            }

            // Stage 4 -  do verification against Context,  IsCompleted  and the TaskStatus
            if (_taskSchedulerType == TaskSchedulerType.CustomWithInlineExecution)
            {
                Assert.Equal(expectedThreadID, _taskThreadID);
            }
            else if (_taskSchedulerType == TaskSchedulerType.CustomWithoutInlineExecution)
            {
                Assert.NotEqual(expectedThreadID, _taskThreadID);
            }
            else if (_taskThreadID != expectedThreadID)
            {
                Debug.WriteLine("Warning: RunSynchronously request ignored -- Task did not run under the same context");
            }

            Assert.True(_task.IsCompleted, "RunSynchronously contract broken -- Task is not complete when the call return");

            if (_workloadType == WorkloadType.ThrowException)
            {
                if (_task.Status != TaskStatus.Faulted)
                {
                    Assert.True(false, string.Format("Wrong final task status on a faulty workload"));
                }

                CheckExpectedAggregateException(_task.Exception);
                //Assert.True(false, string.Format("Fail to record the test exception in Task.Exception"));
            }
            else
            {
                if (_task.Status != TaskStatus.RanToCompletion)
                {
                    Assert.True(false, string.Format("Wrong final task status on a regular workload"));
                }
            }

            //
            // Extra verification to ensure the Task was RunSynchronously on
            // specified TaskScheduler
            //
            if (_taskSchedulerType == TaskSchedulerType.CustomWithInlineExecution ||
                _taskSchedulerType == TaskSchedulerType.CustomWithoutInlineExecution)
            {
                if (((TaskRunSyncTaskScheduler)ts).RunSyncCalledCount <= 0)
                {
                    Assert.True(false, string.Format("Task wasn't RunSynchronously with TaskScheduler specified"));
                }
            }

            // Stage 5 -  follow with the post-action
            switch (_postRunSyncAction)
            {
            case PostRunSyncAction.Wait:
                try
                {
                    if (_postRunSyncAction == PostRunSyncAction.Wait)
                    {
                        _task.Wait(0);
                    }
                    if (_workloadType == WorkloadType.ThrowException)
                    {
                        Assert.True(false, string.Format("expected failure is not propogated out of Wait"));
                    }
                }
                catch (AggregateException ae)
                {
                    CheckExpectedAggregateException(ae);
                }
                break;

            case PostRunSyncAction.Cancel:

                _cts.Cancel();
                break;

            case PostRunSyncAction.ContinueWith:
                _task.ContinueWith((t) => { }).Wait();
                break;
            }

            DisposeScheduler(ts);
        }
Esempio n. 40
0
 public static async Task RunUIAwait(TaskScheduler context, Action func)
 {
     await Task.Factory.StartNew(func, new CancellationToken(), TaskCreationOptions.None, context);
 }
Esempio n. 41
0
        protected override async Task OnUpdate(CancellationToken token, TaskScheduler mainScheduler)
        {
            await Task.Delay(25, token);

            rotation = (rotation + 5) % 360;
        }
Esempio n. 42
0
 protected override void OnLoad(EventArgs e)
 {
     base.OnLoad(e);
     Task.Factory.StartNew(Worker).ContinueWith(t => { this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext());
 }
Esempio n. 43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TaskSchedulerAwaiter"/> struct.
 /// </summary>
 /// <param name="taskScheduler">
 /// The task scheduler.
 /// </param>
 internal TaskSchedulerAwaiter(TaskScheduler taskScheduler)
 {
     this.taskScheduler = taskScheduler;
 }
Esempio n. 44
0
        private void Click_patternReplaceButton(object sender, EventArgs e)
        {
            tagMan.directory            = folderEntry.Text;
            tagMan.moveFilesToDirectory = unfilterButton.Checked;
            tagMan.pattern = replacePattern.Text;
            int result = tagMan.SetMP3Names(ID3Progress);

            if (result == 0)   //renaming succeeded
            {
                ID3Status.Text      = "Operation completed successfully!";
                ID3Status.ForeColor = Color.Green;
                Task.Delay(2000).ContinueWith((Task t) => { ID3Progress.Value = 0; }, TaskScheduler.FromCurrentSynchronizationContext());
            }
            else if (result == 10)     //aborted due to error
            {
                ID3Status.Text      = "Operation cancelled!";
                ID3Status.ForeColor = Color.Red;
            }
            else if (result == 2)     //error ignored
            {
                ID3Status.Text      = "Some files were not renamed due to an error!";
                ID3Status.ForeColor = Color.Red;
            }
        }
 public InfoDialog(string accessToken)
 {
     _accessToken = accessToken;
     _ui          = TaskScheduler.FromCurrentSynchronizationContext();
     InitializeComponent();
 }
Esempio n. 46
0
 public SimpleTask(Action work, Action callback, TaskScheduler sched)  : this(work, callback, null, sched)
 {
 }
Esempio n. 47
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ProgressReporter"/> class. This should be run on a UI thread.
 /// </summary>
 public ProgressReporter()
 {
     this.scheduler = TaskScheduler.FromCurrentSynchronizationContext();
 }
Esempio n. 48
0
 private Task CreateTask(TRequest request, CancellationToken cancellationToken, TaskScheduler orleansTaskScheduler) =>
 Task.Run(async() =>
 {
     try
     {
         var response = await ProcessAsync(request, cancellationToken);
         await InvokeGrainAsync(orleansTaskScheduler, grain => grain.CompleteAsync(response));
     }
     catch (Exception exception)
     {
         await InvokeGrainAsync(orleansTaskScheduler, grain => grain.FailedAsync(exception));
     }
 });
Esempio n. 49
0
        private void OpenFile(string fileName, byte[] input = null, TreeViewWithSearchResults.TreeViewPackageTag currentPackage = null)
        {
            Console.WriteLine($"Opening {fileName}");

            if (input == null && Regex.IsMatch(fileName, @"_[0-9]{3}\.vpk$"))
            {
                var fixedPackage = $"{fileName.Substring(0, fileName.Length - 8)}_dir.vpk";

                if (File.Exists(fixedPackage))
                {
                    Console.WriteLine($"You opened \"{Path.GetFileName(fileName)}\" but there is \"{Path.GetFileName(fixedPackage)}\"");
                    fileName = fixedPackage;
                }
            }

            var tab = new TabPage(Path.GetFileName(fileName));

            tab.ToolTipText = fileName;
            tab.Controls.Add(new LoadingFile());

            mainTabs.TabPages.Add(tab);
            mainTabs.SelectTab(tab);

            var task = Task.Factory.StartNew(() => ProcessFile(fileName, input, currentPackage));

            task.ContinueWith(
                t =>
            {
                t.Exception?.Flatten().Handle(ex =>
                {
                    var control = new TextBox
                    {
                        Dock      = DockStyle.Fill,
                        Font      = new Font(FontFamily.GenericMonospace, 8),
                        Multiline = true,
                        ReadOnly  = true,
                        Text      = ex.ToString(),
                    };

                    tab.Controls.Clear();
                    tab.Controls.Add(control);

                    return(false);
                });
            },
                CancellationToken.None,
                TaskContinuationOptions.OnlyOnFaulted,
                TaskScheduler.FromCurrentSynchronizationContext());

            task.ContinueWith(
                t =>
            {
                tab.Controls.Clear();

                foreach (Control c in t.Result.Controls)
                {
                    tab.Controls.Add(c);
                }
            },
                CancellationToken.None,
                TaskContinuationOptions.OnlyOnRanToCompletion,
                TaskScheduler.FromCurrentSynchronizationContext());
        }
Esempio n. 50
0
 public SearcherFactoryAnonymousInnerClassHelper2(TestSearcherManager outerInstance, CountdownEvent awaitEnterWarm, CountdownEvent awaitClose, AtomicBoolean triedReopen, TaskScheduler es)
 {
     this.OuterInstance  = outerInstance;
     this.AwaitEnterWarm = awaitEnterWarm;
     this.AwaitClose     = awaitClose;
     this.TriedReopen    = triedReopen;
     this.Es             = es;
 }
 protected void CreateDispatchTask()
 {
     //Don't await because we want start to end.
     Task.Factory.StartNew(StartDispatchingAsync, CancelTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.FromCurrentSynchronizationContext())
     .ConfigureAwait(true);
 }
Esempio n. 52
0
 /// <summary>
 /// Create a new Disruptor.
 /// </summary>
 /// <param name="eventFactory">the factory to create events in the ring buffer</param>
 /// <param name="ringBufferSize">the size of the ring buffer, must be power of 2</param>
 /// <param name="taskScheduler">a <see cref="TaskScheduler"/> to create threads for processors</param>
 /// <param name="producerType">the claim strategy to use for the ring buffer</param>
 /// <param name="waitStrategy">the wait strategy to use for the ring buffer</param>
 public Disruptor(Func <T> eventFactory, int ringBufferSize, TaskScheduler taskScheduler, ProducerType producerType, IWaitStrategy waitStrategy)
     : this(RingBuffer <T> .Create(producerType, eventFactory, ringBufferSize, waitStrategy), new BasicExecutor(taskScheduler))
 {
 }
Esempio n. 53
0
        public static int Main(string[] args)
        {
            const bool simpleSubProcess = false;

            Cef.EnableHighDPISupport();

            //NOTE: Using a simple sub processes uses your existing application executable to spawn instances of the sub process.
            //Features like JSB, EvaluateScriptAsync, custom schemes require the CefSharp.BrowserSubprocess to function
            if (simpleSubProcess)
            {
                var exitCode = Cef.ExecuteProcess();

                if (exitCode >= 0)
                {
                    return(exitCode);
                }

#if DEBUG
                if (!System.Diagnostics.Debugger.IsAttached)
                {
                    MessageBox.Show("When running this Example outside of Visual Studio " +
                                    "please make sure you compile in `Release` mode.", "Warning");
                }
#endif

                var settings = new CefSettings();
                settings.BrowserSubprocessPath = "CefSharp.WinForms.Example.exe";

                Cef.Initialize(settings);

                var browser = new SimpleBrowserForm(true);
                Application.Run(browser);
            }
            else
            {
#if DEBUG
                if (!System.Diagnostics.Debugger.IsAttached)
                {
                    MessageBox.Show("When running this Example outside of Visual Studio " +
                                    "please make sure you compile in `Release` mode.", "Warning");
                }
#endif

                //When multiThreadedMessageLoop = true then externalMessagePump must be set to false
                // To enable externalMessagePump set  multiThreadedMessageLoop = false and externalMessagePump = true
                const bool multiThreadedMessageLoop = false;
                const bool externalMessagePump      = false;

                //var browser = new BrowserForm(multiThreadedMessageLoop);
                var browser = new SimpleBrowserForm(multiThreadedMessageLoop);
                //var browser = new TabulationDemoForm();

                IBrowserProcessHandler browserProcessHandler;

                if (multiThreadedMessageLoop)
                {
                    browserProcessHandler = new BrowserProcessHandler();
                }
                else
                {
                    //Get the current taskScheduler (must be called after the form is created)
                    var scheduler = TaskScheduler.FromCurrentSynchronizationContext();

                    if (externalMessagePump)
                    {
                        browserProcessHandler = new ScheduleMessagePumpBrowserProcessHandler(scheduler);
                    }
                    else
                    {
                        browserProcessHandler = new WinFormsBrowserProcessHandler(scheduler);
                    }
                }

                var settings = new CefSettings();
                settings.MultiThreadedMessageLoop = multiThreadedMessageLoop;
                settings.ExternalMessagePump      = externalMessagePump;

                CefExample.Init(settings, browserProcessHandler: browserProcessHandler);

                Application.Run(browser);
            }

            return(0);
        }
Esempio n. 54
0
 public TaskFactory(TaskScheduler scheduler) : base(scheduler)
 {
 }
Esempio n. 55
0
 public SearcherFactoryAnonymousInnerClassHelper(TestSearcherManager outerInstance, TaskScheduler es)
 {
     this.OuterInstance = outerInstance;
     this.Es            = es;
 }
Esempio n. 56
0
        private void Navigate(Uri oldValue, Uri newValue, NavigationType navigationType)
        {
            Debug.WriteLine("Navigating from '{0}' to '{1}'", oldValue, newValue);

            // set IsLoadingContent state
            SetValue(IsLoadingContentPropertyKey, true);

            // cancel previous load content task (if any)
            // note: no need for thread synchronization, this code always executes on the UI thread
            if (this.tokenSource != null)
            {
                this.tokenSource.Cancel();
                this.tokenSource = null;
            }

            // push previous source onto the history stack (only for new navigation types)
            if (oldValue != null && navigationType == NavigationType.New)
            {
                this.history.Push(oldValue);
            }

            object newContent = null;

            if (newValue != null)
            {
                // content is cached on uri without fragment
                var newValueNoFragment = NavigationHelper.RemoveFragment(newValue);

                if (navigationType == NavigationType.Refresh || !this.contentCache.TryGetValue(newValueNoFragment, out newContent))
                {
                    var localTokenSource = new CancellationTokenSource();
                    this.tokenSource = localTokenSource;
                    // load the content (asynchronous!)
                    var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
                    var task      = this.ContentLoader.LoadContentAsync(newValue, this.tokenSource.Token);

                    task.ContinueWith(t => {
                        try {
                            if (t.IsCanceled || localTokenSource.IsCancellationRequested)
                            {
                                Debug.WriteLine("Cancelled navigation to '{0}'", newValue);
                            }
                            else if (t.IsFaulted)
                            {
                                // raise failed event
                                var failedArgs = new NavigationFailedEventArgs {
                                    Frame   = this,
                                    Source  = newValue,
                                    Error   = t.Exception.InnerException,
                                    Handled = false
                                };

                                OnNavigationFailed(failedArgs);

                                // if not handled, show error as content
                                newContent = failedArgs.Handled ? null : failedArgs.Error;

                                SetContent(newValue, navigationType, newContent, true);
                            }
                            else
                            {
                                newContent = t.Result;
                                if (ShouldKeepContentAlive(newContent))
                                {
                                    // keep the new content in memory
                                    this.contentCache[newValueNoFragment] = newContent;
                                }

                                SetContent(newValue, navigationType, newContent, false);
                            }
                        }
                        finally {
                            // clear global tokenSource to avoid a Cancel on a disposed object
                            if (this.tokenSource == localTokenSource)
                            {
                                this.tokenSource = null;
                            }

                            // and dispose of the local tokensource
                            localTokenSource.Dispose();
                        }
                    }, scheduler);
                    return;
                }
            }

            // newValue is null or newContent was found in the cache
            SetContent(newValue, navigationType, newContent, false);
        }
Esempio n. 57
0
        int Run(MonoDevelopOptions options)
        {
            LoggingService.LogInfo("Starting {0} {1}", BrandingService.ApplicationLongName, IdeVersionInfo.MonoDevelopVersion);
            LoggingService.LogInfo("Running on {0}", IdeVersionInfo.GetRuntimeInfo());

            //ensure native libs initialized before we hit anything that p/invokes
            Platform.Initialize();

            LoggingService.LogInfo("Operating System: {0}", SystemInformation.GetOperatingSystemDescription());

            Counters.Initialization.BeginTiming();

            if (options.PerfLog)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.perf-log");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.Initialization.Trace("Initializing GTK");
            if (Platform.IsWindows && !CheckWindowsGtk())
            {
                return(1);
            }
            SetupExceptionManager();

            IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer();
            try {
                IdeApp.Customizer.Initialize();
            } catch (UnauthorizedAccessException ua) {
                LoggingService.LogError("Unauthorized access: " + ua.Message);
                return(1);
            }

            try {
                GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            var args = options.RemainingArgs.ToArray();

            IdeTheme.InitializeGtk(BrandingService.ApplicationName, ref args);

            LoggingService.LogInfo("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion());

            // XWT initialization
            FilePath p = typeof(IdeStartup).Assembly.Location;

            Platform.AssemblyLoad(p.ParentDirectory.Combine("Xwt.Gtk.dll"));
            Xwt.Application.InitializeAsGuest(Xwt.ToolkitType.Gtk);
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarWindowBackend, GtkExtendedTitleBarWindowBackend> ();
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarDialogBackend, GtkExtendedTitleBarDialogBackend> ();
            IdeTheme.SetupXwtTheme();

            //default to Windows IME on Windows
            if (Platform.IsWindows && GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            string   socket_filename = null;
            EndPoint ep = null;

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(DispatchService.SynchronizationContext);
            Runtime.MainSynchronizationContext = SynchronizationContext.Current;

            AddinManager.AddinLoadError += OnAddinError;

            var startupInfo = new StartupInfo(args);

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                Counters.Initialization.Trace("Pre-Initializing Runtime to load files in existing window");
                Runtime.Initialize(true);
                foreach (var file in startupInfo.RequestedFileList)
                {
                    if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                    {
                        options.NewWindow = true;
                        break;
                    }
                }
            }

            Counters.Initialization.Trace("Initializing Runtime");
            Runtime.Initialize(true);

            Composition.CompositionManager.InitializeAsync().Ignore();

            IdeApp.Customizer.OnCoreInitialized();

            Counters.Initialization.Trace("Initializing theme");

            IdeTheme.SetupGtkTheme();

            ProgressMonitor monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();

            monitor.BeginTask(GettextCatalog.GetString("Starting {0}", BrandingService.ApplicationName), 2);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.Initialization.Trace("Initializing Platform Service");
            DesktopService.Initialize();

            monitor.Step(1);

            if (options.IpcTcp)
            {
                listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ep            = new IPEndPoint(IPAddress.Loopback, ipcBasePort + HashSdbmBounded(Environment.UserName));
            }
            else
            {
                socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable("USER") + "-socket";
                listen_socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                ep = new UnixEndPoint(socket_filename);
            }

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles)
            {
                try {
                    StringBuilder builder = new StringBuilder();
                    foreach (var file in startupInfo.RequestedFileList)
                    {
                        builder.AppendFormat("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
                    }
                    listen_socket.Connect(ep);
                    listen_socket.Send(Encoding.UTF8.GetBytes(builder.ToString()));
                    return(0);
                } catch {
                    // Reset the socket
                    if (null != socket_filename && File.Exists(socket_filename))
                    {
                        File.Delete(socket_filename);
                    }
                }
            }

            Counters.Initialization.Trace("Checking System");

            CheckFileWatcher();

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.Initialization.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();
                LocalizationService.Initialize();

                // If we display an error dialog before the main workbench window on OS X then a second application menu is created
                // which is then replaced with a second empty Apple menu.
                // XBC #33699
                Counters.Initialization.Trace("Initializing IdeApp");
                IdeApp.Initialize(monitor);

                if (errorsList.Count > 0)
                {
                    using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), false)) {
                        if (!dlg.Run())
                        {
                            return(1);
                        }
                    }
                    reportedFailures = errorsList.Count;
                }

                if (!CheckSCPlugin())
                {
                    return(1);
                }

                // Load requested files
                Counters.Initialization.Trace("Opening Files");

                // load previous combine
                RecentFile openedProject = null;
                if (IdeApp.Preferences.LoadPrevSolutionOnStartup && !startupInfo.HasSolutionFile && !IdeApp.Workspace.WorkspaceItemIsOpening && !IdeApp.Workspace.IsOpen)
                {
                    openedProject = DesktopService.RecentFiles.MostRecentlyUsedProject;
                    if (openedProject != null)
                    {
                        var metadata = GetOpenWorkspaceOnStartupMetadata();
                        IdeApp.Workspace.OpenWorkspaceItem(openedProject.FileName, true, true, metadata).ContinueWith(t => IdeApp.OpenFiles(startupInfo.RequestedFileList, metadata), TaskScheduler.FromCurrentSynchronizationContext());
                        startupInfo.OpenedRecentProject = true;
                    }
                }
                if (openedProject == null)
                {
                    IdeApp.OpenFiles(startupInfo.RequestedFileList, GetOpenWorkspaceOnStartupMetadata());
                    startupInfo.OpenedFiles = startupInfo.HasFiles;
                }

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                string message = BrandingService.BrandApplicationName(GettextCatalog.GetString("MonoDevelop failed to start"));
                MessageService.ShowFatalError(message, null, error);
                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), true))
                    dlg.Run();
            }

            errorsList = null;
            AddinManager.AddinLoadError -= OnAddinError;

            // FIXME: we should probably track the last 'selected' one
            // and do this more cleanly
            try {
                listen_socket.Bind(ep);
                listen_socket.Listen(5);
                listen_socket.BeginAccept(new AsyncCallback(ListenCallback), listen_socket);
            } catch {
                // Socket already in use
            }

            initialized = true;
            MessageService.RootWindow    = IdeApp.Workbench.RootWindow;
            Xwt.MessageDialog.RootWindow = Xwt.Toolkit.CurrentEngine.WrapWindow(IdeApp.Workbench.RootWindow);
            Thread.CurrentThread.Name    = "GUI Thread";
            Counters.Initialization.Trace("Running IdeApp");
            Counters.Initialization.EndTiming();

            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);
            StartLockupTracker();

            startupTimer.Stop();
            Counters.Startup.Inc(GetStartupMetadata(startupInfo));

            IdeApp.Run();

            IdeApp.Customizer.OnIdeShutdown();

            // unloading services
            if (null != socket_filename)
            {
                File.Delete(socket_filename);
            }
            lockupCheckRunning = false;
            Runtime.Shutdown();

            IdeApp.Customizer.OnCoreShutdown();

            InstrumentationService.Stop();

            MonoDevelop.Components.GtkWorkarounds.Terminate();

            return(0);
        }
 public static Task Error(this Task task, Action <Exception> fn,
                          bool onUiThread = true,
                          TaskContinuationOptions taskOptions = TaskContinuationOptions.OnlyOnFaulted)
 {
     if (onUiThread)
     {
         var source = new CancellationToken();
         task.ContinueWith(t => fn(t.UnwrapIfSingleException()), source, taskOptions, TaskScheduler.FromCurrentSynchronizationContext());
     }
     else
     {
         task.ContinueWith(t => fn(t.UnwrapIfSingleException()), taskOptions);
     }
     return(task);
 }
Esempio n. 59
0
        public void RaiseAsync(InteractionMessage message)
        {
            if (message == null)
            {
                throw new ArgumentException("messageはnullにできません");
            }

            if (!message.IsFrozen)
            {
                message.Freeze();
            }

            var task = Task.Factory.StartNew(() => Raise(message), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

            task.ContinueWith(t =>
            {
                var e = new AsyncMessageFailedEventArgs(t.Exception);
                OnAsyncMessageFailed(e);
                t.Exception.Handle(ex => true);
            }, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);
        }
Esempio n. 60
0
        }                                                           // TODO: -> private

        public static void Initialize()
        {
            Scheduler = TaskScheduler.FromCurrentSynchronizationContext();
        }