示例#1
0
        /// <summary>
        /// Execute non query command asyncronously.
        /// </summary>
        /// <param name="command">The complete command</param>
        /// <param name="callback">The callback action handler.</param>
        /// <param name="callbackException">The callback action exception handler.</param>
        /// <param name="state">The action state.</param>
        public static async void ExecuteCommand(DbCommand command,
                                                Action <Nequeo.Threading.AsyncOperationResult <Int32> > callback,
                                                Action <Nequeo.Threading.AsyncOperationResult <System.Exception> > callbackException, object state = null)
        {
            // Check to see if the critical parameters
            // have been set, throw exception on each.
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            AsyncExecuteCommand ret = new AsyncExecuteCommand(command, null, null);

            System.Threading.Tasks.Task <Int32> data = Task <Int32> .Factory.FromAsync(ret.BeginExecute(), ret.EndExecute);

            Int32 commandAsyncResult = await data;

            if (callback != null)
            {
                callback(new Nequeo.Threading.AsyncOperationResult <Int32>(commandAsyncResult, state, "ExecuteCommand"));
            }

            if (callbackException != null)
            {
                callbackException(new Nequeo.Threading.AsyncOperationResult <System.Exception>(ret.Exception, state, "ExecuteCommand"));
            }
        }
示例#2
0
文件: 13.cs 项目: qifanyyy/CLCDSA
        public override void Solve()
        {
            string sLines = Console.ReadLine();
            int    iCases = int.Parse(sLines);

            System.Threading.Tasks.Task <string>[] tasks = new System.Threading.Tasks.Task <string> [iCases];

            for (int iCase = 1; iCase <= iCases; iCase++)
            {
                int      N    = int.Parse(Console.ReadLine());
                string[] s    = Console.ReadLine().Split();
                int[]    bffs = s.Select <string, int>(bff => int.Parse(bff)).ToArray();
                tasks[iCase - 1] = System.Threading.Tasks.Task.Run <string>
                                   (
                    () => DoWork(N, bffs)
                                   );
                //tasks[iCase - 1].Wait();
            }

            for (int iCase = 1; iCase <= iCases; iCase++)
            {
                string ret = tasks[iCase - 1].Result;
                Console.WriteLine("Case #{0}: {1}", iCase, ret);
                System.Diagnostics.Debug.WriteLine("Case #{0}: {1}", iCase, ret);
            }
        }
示例#3
0
        public static void TASK_TestContractA_TwoWayCall_Timeout(string CONF_SRC)
        {
            TestServerA.s_Accumulator = 0;

            var conf = LaconicConfiguration.CreateFromString(CONF_SRC);

            using (var app = new AzosApplication(null, conf.Root))
            {
                var cl = new TestContractAClient(app.Glue, app.ConfigRoot.AttrByName("cs").Value);
                cl.TimeoutMs = 2000;

                System.Threading.Tasks.Task <CallSlot> task = null;
                try
                {
                    task = cl.Async_Sleeper(10000).AsTask;
                    task.Result.GetValue <int>();
                }
                catch (ClientCallException err)
                {
                    Aver.IsTrue(CallStatus.Timeout == err.Status);
                    return;
                }
                catch (System.IO.IOException err) //sync binding throws IO exception
                {
                    Aver.IsTrue(err.Message.Contains("after a period of time"));
                    return;
                }

                Aver.Fail("Invalid Call status: " + (task != null ? task.Result.CallStatus.ToString() : "task==null"));
            }
        }
示例#4
0
        private string getUserName(string accessToken)
        {
#if DEBUG
            if (accessToken == "me")
            {
                return("david");
            }
#endif

            AddInSsoToken ssotoken = new AddInSsoToken(accessToken);


            string expectedAudience = ConfigurationManager.AppSettings["ida:Audience"];
            string expectedIssuer   = ConfigurationManager.AppSettings["ida:Issuer"];

            System.Threading.Tasks.Task <SsoTokenValidationResult> task = System.Threading.Tasks.Task.Run <SsoTokenValidationResult>(async() => await ssotoken.Validate(expectedAudience, expectedIssuer));

            if (task.Result.IsValid == false)
            {
                Log.Error(task.Result.Message);
                Log.Info(accessToken);
            }

            return(task.Result.PreferredName);
        }
示例#5
0
        public IActionResult GetRandomPoll()
        {
            Random r = new Random();

            System.Threading.Tasks.Task <int> noOfPolls = _yPollRepository.Table.CountAsync <Poll>();
            int pollNumber = r.Next(0, noOfPolls.Result - 1);
            IEnumerator <Poll> enumerator = _yPollRepository.Table.GetEnumerator();
            int  position = 0;
            Poll selectedPoll;

            while (enumerator.MoveNext())
            {
                selectedPoll = enumerator.Current;
                if ((selectedPoll != null) && (position == pollNumber))
                {
                    return(Json(selectedPoll));
                }
                else if ((selectedPoll == null) && (position >= pollNumber))
                {
                    enumerator.Reset();
                    if (enumerator.MoveNext())
                    {
                        selectedPoll = enumerator.Current;
                        return(Json(selectedPoll));
                    }
                }
                position = position + 1;
            }
            return(new Nop.Web.Framework.Mvc.NullJsonResult());
            // int pollNumber = _pollExtensionService.GetRandomPollNumber();
            // return _pollExtensionService.GetPollRecord(new Poll {Id = pollNumber});
        }
示例#6
0
        /// <summary>
        /// Asynchronous array combining operation; appends to the end of the source array.
        /// </summary>
        /// <param name="source">The source array.</param>
        /// <param name="arrayOne">The first combining array.</param>
        /// <param name="arrayTwo">The second combining array.</param>
        /// <param name="arrayThree">The third combining array.</param>
        /// <param name="arrayFour">The fourth combining array.</param>
        public async void Combine(Byte[] source, Byte[] arrayOne, Byte[] arrayTwo, Byte[] arrayThree, Byte[] arrayFour)
        {
            // If the source object is null.
            if (source == null)
            {
                throw new System.ArgumentNullException("source");
            }
            if (arrayOne == null)
            {
                throw new System.ArgumentNullException("arrayOne");
            }
            if (arrayTwo == null)
            {
                throw new System.ArgumentNullException("arrayTwo");
            }
            if (arrayThree == null)
            {
                throw new System.ArgumentNullException("arrayThree");
            }
            if (arrayFour == null)
            {
                throw new System.ArgumentNullException("arrayFour");
            }

            System.Threading.Tasks.Task <Byte[]> data = source.CombineParallelAsync(arrayOne, arrayTwo, arrayThree, arrayFour);
            _byteAsyncResult = await data;

            if (AsyncComplete != null)
            {
                AsyncComplete(this, new EventArgs());
            }
        }
示例#7
0
        public override void Solve()
        {
            string sLines = Console.ReadLine();
            int    iCases = int.Parse(sLines);

            System.Threading.Tasks.Task <string>[] tasks = new System.Threading.Tasks.Task <string> [iCases];

            for (int iCase = 1; iCase <= iCases; iCase++)
            {
                string[] s = Console.ReadLine().Split();
                string   C = s[0];
                string   J = s[1];
                tasks[iCase - 1] = System.Threading.Tasks.Task.Run <string>
                                   (
                    () => DoWork(C, J)
                                   );
                tasks[iCase - 1].Wait();
            }

            for (int iCase = 1; iCase <= iCases; iCase++)
            {
                string ret = tasks[iCase - 1].Result;
                Console.WriteLine("Case #{0}: {1}", iCase, ret);
                System.Diagnostics.Debug.WriteLine("Case #{0}: {1}", iCase, ret);
            }
        }
示例#8
0
        private ODataEntry WriteEntity(Edm edm, string url, string entitySetName, IDictionary <string, object> data)
        {
            ODataClient client = new ODataClient(new System.Uri(url));

            System.Threading.Tasks.Task <IDictionary <string, object> > task = client.For(entitySetName).Set(data).InsertEntryAsync();
            WaitForTaskToComplete(task);

            Exception e = task.Exception;

            if (e != null)
            {
                if (e.InnerException is Simple.OData.Client.WebRequestException)
                {
                    // this means we got a response from the server with a specific message.
                    Simple.OData.Client.WebRequestException inner = (Simple.OData.Client.WebRequestException)e.InnerException;
                    NeotysAPIException napie = NeotysAPIException.Parse(inner.Response);
                    if (napie != null)
                    {
                        throw napie;
                    }
                    throw inner;
                }
                throw e;
            }

            IDictionary <string, object> result = task.Result;
            ODataEntry returnValue = new ODataEntry(result);

            return(returnValue);
        }
示例#9
0
文件: 13.cs 项目: qifanyyy/CLCDSA
        public override void Solve()
        {
            string sLines = Console.ReadLine();
            int    iCases = int.Parse(sLines);

            System.Threading.Tasks.Task <string>[] tasks = new System.Threading.Tasks.Task <string> [iCases];

            for (int iCase = 1; iCase <= iCases; iCase++)
            {
                int N = int.Parse(Console.ReadLine());
                int[,] vals = new int[2 * N - 1, N];
                for (int a = 0; a < 2 * N - 1; a++)
                {
                    string[] s = Console.ReadLine().Split();
                    for (int i = 0; i < N; i++)
                    {
                        vals[a, i] = int.Parse(s[i]);
                    }
                }
                tasks[iCase - 1] = System.Threading.Tasks.Task.Run <string>
                                   (
                    () => DoWork(N, vals)
                                   );
            }

            for (int iCase = 1; iCase <= iCases; iCase++)
            {
                string ret = tasks[iCase - 1].Result;
                Console.WriteLine("Case #{0}: {1}", iCase, ret);
                System.Diagnostics.Debug.WriteLine("Case #{0}: {1}", iCase, ret);
            }
        }
示例#10
0
        private RuleDetails GetRuleDetailsFromToken(string shareToken)
        {
            RuleDetails ruleDetails = null;

            try
            {
                System.Threading.Tasks.Task <RuleDetails> ruleTask = System.Threading.Tasks.Task.Run(new Func <RuleDetails>(() =>
                {
                    //return WebService.RemoteRuleService.GetRemoteRuleAsync(watermakTextBox_ruleToken.Text).GetAwaiter().GetResult();
                    return(shareRuleService.GetShareRuleDetailAsync(shareToken).GetAwaiter().GetResult());
                }));
                ruleDetails = ruleTask.GetAwaiter().GetResult();
                if (ruleDetails == null)
                {
                    MessageBox.Show("your rule token is not permitted", "Stop", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                else if (ruleDetails.ModificHttpRuleCollection == null || ((ruleDetails.ModificHttpRuleCollection.RequestRuleList == null || ruleDetails.ModificHttpRuleCollection.RequestRuleList.Count == 0) && (ruleDetails.ModificHttpRuleCollection.ResponseRuleList == null || ruleDetails.ModificHttpRuleCollection.ResponseRuleList.Count == 0)))
                {
                    MessageBox.Show("can not find any rule in your storage spaces", "Stop", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    ruleDetails = null;
                }
            }
            catch (Exception ex)
            {
                _           = RemoteLogService.ReportLogAsync(ex.ToString(), RemoteLogService.RemoteLogOperation.RemoteRule, RemoteLogService.RemoteLogType.Error);
                ruleDetails = null;
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return(ruleDetails);
        }
示例#11
0
        public override void Solve()
        {
            string sLines = Console.ReadLine();
            int    iCases = int.Parse(sLines);

            System.Threading.Tasks.Task <string>[] tasks = new System.Threading.Tasks.Task <string> [iCases];

            for (int iCase = 1; iCase <= iCases; iCase++)
            {
                int N = int.Parse(Console.ReadLine());
                string[,] s = new string[N, 2];
                for (int i = 0; i < N; i++)
                {
                    string[] sLine = Console.ReadLine().Split(' ');
                    s[i, 0] = sLine[0];
                    s[i, 1] = sLine[1];
                }
                tasks[iCase - 1] = System.Threading.Tasks.Task.Run <string>
                                   (
                    () => DoWork(N, s)
                                   );
                //tasks[iCase - 1].Wait();
            }

            for (int iCase = 1; iCase <= iCases; iCase++)
            {
                string ret = tasks[iCase - 1].Result;
                Console.WriteLine("Case #{0}: {1}", iCase, ret);
                System.Diagnostics.Debug.WriteLine("Case #{0}: {1}", iCase, ret);
            }
        }
示例#12
0
        // ==================================================


        internal static void Run()
        {
            // Create a connection object, which we will use to get httpclient objects.  This is more robust
            // then newing up httpclient objects directly.  Be sure to send in the full collection uri.
            // For example:  http://myserver:8080/tfs/defaultcollection
            // We are using default VssCredentials which uses NTLM against a Team Foundation Server.  See additional provided
            // examples for creating credentials for other types of authentication.

            VssConnection connection = new VssConnection(new Uri(GIT_IGNORE.Variables.AdoUri__TEST__),
                                                         new VssAadCredential(GIT_IGNORE.Variables.AdoMagicWord1, GIT_IGNORE.Variables.AdoMagicWord2));

            // Create instance of WorkItemTrackingHttpClient using VssConnection
            WorkItemTrackingHttpClient witClient = connection.GetClient <WorkItemTrackingHttpClient>();

            System.Threading.Tasks.Task <List <WorkItem> > workItems = witClient.GetWorkItemsAsync(new int[] { 5, 1 });

            // System.Threading.Tasks.Task<List<WorkItem>> workItems = witClient.GetWorkItemsAsync(new int[] { }, null, DateTime.Now.AddDays(-1));

            // WorkItem result = witClient.CreateWorkItemAsync(patchDocument, _PROJECT, newItemType).Result;

            foreach (var item in workItems.Result)
            {
                Console.WriteLine(item.Id);
                Console.WriteLine(item.Url);
                Console.WriteLine();
            }
        }
示例#13
0
        /// <summary>
        /// 同步方法调用
        /// </summary>
        /// <param name="taskModel">操作实体类</param>
        /// <returns>返回结果</returns>
        public Object ExecuteCmd(TaskModelBase taskModel)
        {
            object backObj = null;

            try
            {
                using (System.Threading.Tasks.Task <Object> result = System.Threading.Tasks.Task.Run <object>(() =>
                {
                    IOperator _operator = null;

                    try
                    {
                        _operator = operatorFactory.CreateOperator(taskModel.operatorName);
                        _operator.taskModel = taskModel;
                    }
                    catch
                    {
                    }
                    return(_operator.doOperator());
                }))
                {
                    backObj = result.Result;
                };
            }
            catch (Exception ex)
            {
                iCMS.WG.Agent.Common.LogHelper.WriteLog(iCMS.WG.Agent.Common.Enum.EnumLogType.Error.ToString(), "iCMS.WG.Agent.SyncTools.ExecuteCmd 执行上层命令失败,异常:" + ex.Message + "\r\n详细:" + ex.StackTrace.ToString());
            }

            return(backObj);
        }
示例#14
0
        private void btnTaskSub_Click(object sender, EventArgs e)
        {//前面提到了,当你等待一个任务的时候,同时需要等待它的子任务完成。
         //下面代码演示了带子任务的Task:

            System.Threading.Tasks.Task <int[]> parentTask = System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                int[] results = new int[3];

                System.Threading.Tasks.Task t1 = new System.Threading.Tasks.Task(() =>
                                                                                 { System.Threading.Thread.Sleep(3000); results[0] = 0; }, TaskCreationOptions.AttachedToParent);
                System.Threading.Tasks.Task t2 = new System.Threading.Tasks.Task(() =>
                                                                                 { System.Threading.Thread.Sleep(3000); results[1] = 1; }, TaskCreationOptions.AttachedToParent);
                System.Threading.Tasks.Task t3 = new System.Threading.Tasks.Task(() =>
                                                                                 { System.Threading.Thread.Sleep(3000); results[2] = 2; }, TaskCreationOptions.AttachedToParent);

                t1.Start();
                t2.Start();
                t3.Start();

                return(results);
            });

            System.Threading.Tasks.Task finalTask = parentTask.ContinueWith(parent =>
            {
                foreach (int result in parent.Result)
                {
                    Console.WriteLine(result);
                }
            });

            finalTask.Wait();
            Console.ReadLine();
            //这段代码的输出结果是: 1,2,3
            //FinalTask会等待所有子Task结束后再执行。
        }
示例#15
0
        public override async System.Threading.Tasks.Task RefreshAsync(ModelRefreshType refreshType, bool showTrackedOperation = true)
        {
            Messenger.Default.Send(new UpdateWaitSpinnerMessage(WaitSpinnerPanel.UpperRight, true));

            if (refreshType.HasFlag(ModelRefreshType.Basic))
            {
                try
                {
                    System.Threading.Tasks.Task asyncTask = this.Job.RefreshAsync(OptionsModel.Instance.ListDetailLevel);
                    if (showTrackedOperation)
                    {
                        AsyncOperationTracker.Instance.AddTrackedOperation(new AsyncOperationModel(
                                                                               asyncTask,
                                                                               new JobOperation(JobOperation.Refresh, this.Job.Id)));
                    }
                    else
                    {
                        AsyncOperationTracker.Instance.AddTrackedInternalOperation(asyncTask);
                    }

                    await asyncTask;
                    this.LastUpdatedTime = DateTime.UtcNow;

                    //
                    // Fire property change events for this models properties
                    //
                    this.FireChangesOnRefresh(ModelRefreshType.Basic);
                }
                catch (Exception e)
                {
                    this.HandleException(e);
                }
            }

            if (refreshType.HasFlag(ModelRefreshType.Children))
            {
                try
                {
                    //Set this before the children load so that on revisit we know we have loaded the children (or are in the process)
                    this.HasLoadedChildren = true;

                    System.Threading.Tasks.Task <List <TaskModel> > asyncTask = this.ListTasksAsync();
                    AsyncOperationTracker.Instance.AddTrackedOperation(new AsyncOperationModel(
                                                                           asyncTask,
                                                                           new JobOperation(JobOperation.ListTasks, this.Job.Id)));

                    this.Tasks          = await asyncTask;
                    this.TaskCollection = CollectionViewSource.GetDefaultView(this.Tasks);
                    this.UpdateTaskView();
                }
                catch (Exception e)
                {
                    this.HasLoadedChildren = false; //On exception, we failed to load children so try again next time
                    this.HandleException(e);
                }
            }

            Messenger.Default.Send(new UpdateWaitSpinnerMessage(WaitSpinnerPanel.UpperRight, false));
            Messenger.Default.Send(new JobUpdateCompleteMessage());
        }
示例#16
0
        private async Task TakeImage()
        {
            var cameraOpts = new CameraMediaStorageOptions();

            cameraOpts.PercentQuality    = 50;
            cameraOpts.MaxPixelDimension = 1200;

            var result = await UIUtils.ShowSelectList("Take a photo", "Choose from library", this);

            System.Threading.Tasks.Task <MediaFile> taskMedia = null;
            if (result == 1)
            {
                taskMedia = DependencyService.Get <IMediaPicker>().TakePhotoAsync(cameraOpts);
            }
            else if (result == 2)
            {
                taskMedia = DependencyService.Get <IMediaPicker>().SelectPhotoAsync(cameraOpts);
            }
            else
            {
                return;
            }
            await taskMedia.ContinueWith((t, o) =>
            {
                if (t.IsCanceled || t.Result == null)
                {
                    return;
                }
                photoFile = t.Result;
            }, null);
        }
示例#17
0
        public string GetServerList(string url)
        {
            try
            {
                HttpClient httpClient = new HttpClient();
                httpClient.Timeout = new TimeSpan(1, 1, 1);
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppContext.Token);

                System.Threading.Tasks.Task <HttpResponseMessage> responseTask = httpClient.GetAsync(url);
                responseTask.Wait();
                HttpResponseMessage response = responseTask.Result;

                System.Threading.Tasks.Task <String> strContentTask = response.Content.ReadAsStringAsync();

                strContentTask.Wait();
                string strContent = strContentTask.Result;

                return(strContent);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Somethink Wrong Error: " + ex.Message);
                return("");
            }
        }
示例#18
0
 public override void Execute(MonitorWorkItem workItem, ITaskExecutionContext context)
 {
     Uri[] uriArray = PingUrlsStep.ParseUrls(workItem.Configuration.PingUrls.Urls, context.Log);
     if (uriArray.Length == 0)
     {
         return;
     }
     try
     {
         Parallel.ForEach <Uri>(uriArray, new ParallelOptions()
         {
             MaxDegreeOfParallelism = 4
         }, (Uri url) => {
             Stopwatch stopwatch = Stopwatch.StartNew();
             try
             {
                 System.Threading.Tasks.Task <HttpResponseMessage> task = this.HttpGet(url, workItem.Configuration.PingUrls.MaximumWaitTimeSeconds);
                 task.Wait();
                 task.Result.EnsureSuccessStatusCode();
             }
             catch (Exception exception)
             {
                 throw new PingUrlsStep.PingException(url, stopwatch, exception);
             }
         });
     }
     catch (AggregateException aggregateException)
     {
         PingUrlsStep.PingException[] pingExceptionArray = PingUrlsStep.AssertExceptions(aggregateException);
         for (int i = 0; i < (int)pingExceptionArray.Length; i++)
         {
             this.AddException(pingExceptionArray[i], workItem);
         }
     }
 }
示例#19
0
        /// <summary>
        /// Gets the stream of a Core ML model file (.mlmodel) of a custom classifier that returns "core_ml_enabled": true in the classifier details.
        /// </summary>
        /// <param name="classifierId"></param>
        /// <returns>The Core ML model of the requested classifier.</returns>
        public Task <Stream> GetCoreMlModel(string classifierId, Dictionary <string, object> customData = null)
        {
            if (string.IsNullOrEmpty(classifierId))
            {
                throw new ArgumentNullException(nameof(classifierId));
            }

            System.Threading.Tasks.Task <Stream> result = null;

            try
            {
                var request = this.Client.GetAsync($"{this.Endpoint}/v3/classifiers/{classifierId}/core_ml_model");
                request.WithArgument("api_key", ApiKey);
                request.WithArgument("version", VersionDate);
                request.WithArgument("classifier_id", classifierId);
                request.WithFormatter(MediaTypeHeaderValue.Parse("application/octet-stream"));
                result = request.AsStream();
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
        private async Task UpdateJobsAsync()
        {
            try
            {
                this.IsBusy = true;
                System.Threading.Tasks.Task <List <JobModel> > asyncTask = this.ListJobsAsync();
                AsyncOperationTracker.Instance.AddTrackedOperation(new AsyncOperationModel(
                                                                       asyncTask,
                                                                       new WorkItemOperation(
                                                                           WorkItemOperation.ListJobs,
                                                                           this.WorkItem.Name)));

                List <JobModel> newItems = await asyncTask;
                this.Jobs = newItems.OrderByDescending(j => j.Name).ToList();
                this.FirePropertyChangedEvent("Jobs");
            }
            catch (Exception e)
            {
                // Notify user
                Messenger.Default.Send <GenericDialogMessage>(new GenericDialogMessage(e.ToString()));
            }
            finally
            {
                this.IsBusy = false;
            }
        }
示例#21
0
        public void ExecuteNonQueryAndScalarAsync()
        {
            if (st.Version < new Version(5, 0))
            {
                return;
            }

            st.execSQL("CREATE TABLE test (id int)");
            st.execSQL("DROP PROCEDURE IF EXISTS spTest");
            st.execSQL("CREATE PROCEDURE spTest() BEGIN SET @x=0; REPEAT INSERT INTO test VALUES(@x); " +
                       "SET @x=@x+1; UNTIL @x = 100 END REPEAT; END");

            EFMySqlCommand proc = new EFMySqlCommand()
            {
                CommandText = "spTest", Connection = st.conn
            };

            proc.CommandType = CommandType.StoredProcedure;
            System.Threading.Tasks.Task <int> result = proc.ExecuteNonQueryAsync();

            Assert.NotEqual(-1, result.Result);

            EFMySqlCommand cmd = new EFMySqlCommand()
            {
                CommandText = "SELECT COUNT(*) FROM test;", Connection = st.conn
            };

            cmd.CommandType = CommandType.Text;
            object cnt = cmd.ExecuteScalarAsync().Result;

            Assert.Equal(100, Convert.ToInt32(cnt));
        }
示例#22
0
        public string AcquireLeaseOnBlob(
            string blob,
            TimeSpan?maxWaitDefault = null,
            TimeSpan?delayDefault   = null)
        {
            TimeSpan maxWait = maxWaitDefault ?? TimeSpan.FromSeconds(120);
            TimeSpan delay   = delayDefault ?? TimeSpan.FromMilliseconds(500);

            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();

            // This will throw an exception with HTTP code 409 when we cannot acquire the lease
            // But we should block until we can get this lease, with a timeout (maxWaitSeconds)
            while (stopWatch.ElapsedMilliseconds < maxWait.TotalMilliseconds)
            {
                try
                {
                    CloudBlockBlob cloudBlob = _blobContainer.GetBlockBlobReference(blob);
                    System.Threading.Tasks.Task <string> task = cloudBlob.AcquireLeaseAsync(TimeSpan.FromMinutes(1), null);
                    task.Wait();
                    return(task.Result);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Retrying lease acquisition on {blob}, {e.Message}");
                    Thread.Sleep(delay);
                }
            }

            throw new Exception($"Unable to acquire lease on {blob}");
        }
示例#23
0
        public override void Solve()
        {
            string sLines = Console.ReadLine();
            int    iCases = int.Parse(sLines);

            System.Threading.Tasks.Task <string>[] tasks = new System.Threading.Tasks.Task <string> [iCases];

            for (int iCase = 1; iCase <= iCases; iCase++)
            {
                string[] s = Console.ReadLine().Split();
                int      N = int.Parse(s[0]);
                int      R = int.Parse(s[1]);
                int      O = int.Parse(s[2]);
                int      Y = int.Parse(s[3]);
                int      G = int.Parse(s[4]);
                int      B = int.Parse(s[5]);
                int      V = int.Parse(s[6]);
                tasks[iCase - 1] = System.Threading.Tasks.Task.Run <string>
                                   (
                    () => DoWorkEasy(N, R, O, Y, G, B, V)
                                   );
                //tasks[iCase - 1].Wait();
            }

            for (int iCase = 1; iCase <= iCases; iCase++)
            {
                string ret = tasks[iCase - 1].Result;
                Console.WriteLine("Case #{0}: {1}", iCase, ret);
                System.Diagnostics.Debug.WriteLine("Case #{0}: {1}", iCase, ret);
            }
        }
示例#24
0
文件: Channel.cs 项目: notflan/Sync
        /// <summary>
        /// Receive an arbitary object asynchronously.
        /// </summary>
        public async System.Threading.Tasks.Task <object> ReceiveAsync()
        {
            var ts = new System.Threading.Tasks.Task <object>(() => Receive());

            ts.Start();
            return(await ts);
        }
        //
        // Once full OM support is added, we can remove all protocol based job operations
        //

        /// <summary>
        /// TODO: This is a hack because Job.Refresh breaks using the job due to its ParentWorkItem name being invalidated in the property router
        /// </summary>
        public ICloudJob GetJob(string workItemName, string jobName, DetailLevel detailLevel)
        {
            using (System.Threading.Tasks.Task <ICloudJob> getJobTask = this.GetJobAsync(workItemName, jobName, detailLevel))
            {
                getJobTask.Wait();
                return(getJobTask.Result);
            }
        }
        public virtual int Count()
        {
            System.Threading.Tasks.Task <int> count = repository.Count();

            count.Wait();

            return(count.Result);
        }
示例#27
0
 public CloudJob GetJob(string jobId, DetailLevel detailLevel)
 {
     using (System.Threading.Tasks.Task <CloudJob> getJobTask = this.GetJobAsync(jobId, detailLevel))
     {
         getJobTask.Wait();
         return(getJobTask.Result);
     }
 }
示例#28
0
 public NotifyTaskCompletion(System.Threading.Tasks.Task<TResult> task)
 {
     Task = task;
     if (!task.IsCompleted)
     {
         var _ = WatchTaskAsync(task);
     }
 }
示例#29
0
        public string AcquireLeaseOnBlob(string blob)
        {
            CloudBlockBlob cloudBlob = _blobContainer.GetBlockBlobReference(blob);

            System.Threading.Tasks.Task <string> task = cloudBlob.AcquireLeaseAsync(TimeSpan.FromMinutes(1), null);
            task.Wait();
            return(task.Result);
        }
示例#30
0
        public Task <bool> GetTwoFactorEnabledAsync(IdentityUser user)
        {
            System.Threading.Tasks.Task <bool> task = System.Threading.Tasks.Task <bool> .Factory.StartNew(() =>
            {
                return(false);
            });

            return(task);
        }
示例#31
0
		public Task<HandlerResult> Start()
		{
			connectionTask =
				connection.Run(cancelSource.Token)
				.ContinueWith(task => {
					if (this.channel!=null) {
						this.channel.RemoveOutputStream(this);
					}
          return HandlerResult.Close;
				});
      return connectionTask;
		}
 private async void SimilarTasksWithWhenAny(object sender, RoutedEventArgs e)
 {
     ResultTextBlock.Text = "Testing... Please Wait.";
     var timer = new System.Diagnostics.Stopwatch();
     timer.Start();
     var tokenSource = new System.Threading.CancellationTokenSource();
     var tasks = new System.Threading.Tasks.Task<string>[10] {
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
         CancellableDummyTask(new Uri("http://stackoverflow.com/"), tokenSource.Token),
     };
     var results = await System.Threading.Tasks.Task.WhenAny<string>(tasks);
     tokenSource.Cancel();
     timer.Stop();
     ResultTextBlock.Text = "Scenario: Similar Tasks Scenario With WhenAny.\n" + timer.Elapsed.TotalMilliseconds + " Milli Seconds the First Task to Complete.";
 }
 private async void MultipleTasksWithWhenAll(object sender, RoutedEventArgs e)
 {
     ResultTextBlock.Text = "Testing... Please Wait.";
     var timer = new System.Diagnostics.Stopwatch();
     timer.Start();
     var tasks = new System.Threading.Tasks.Task<string>[10] {
         DummyTask(new Uri("http://stackoverflow.com/")),
         DummyTask(new Uri("http://www.goal.com/")),
         DummyTask(new Uri("http://www.yallakora.com/")),
         DummyTask(new Uri("https://www.jumia.com.eg/")),
         DummyTask(new Uri("http://www.gsmarena.com/")),
         DummyTask(new Uri("http://www.phonearena.com/")),
         DummyTask(new Uri("http://www.gadget.com/")),
         DummyTask(new Uri("http://www.engadget.com/")),
         DummyTask(new Uri("https://www.yashry.com/")),
         DummyTask(new Uri("https://compume.com.eg/")),
     };
     var results = await System.Threading.Tasks.Task.WhenAll<string>(tasks);
     timer.Stop();
     ResultTextBlock.Text = "Scenario: Multiple Tasks Scenario With WhenAll.\n" + timer.Elapsed.TotalMilliseconds + " Milli Seconds for 10 Tasks to Finish.";
 }