コード例 #1
0
        public Task <MiningResultDto> RentTimeOnLocalMiningServerTask(string authToken, int requestedIterations)
        {
            if (!AuthorizeTheToken(authToken))
            {
                throw new Exception("Failed Authorization");
            }

            var tcs = new TaskCompletionSource <MiningResultDto>();

            var result              = new MiningResultDto();
            var startTime           = DateTime.UtcNow;
            var localMiningTaskList = new List <Task <MiningResultDto> >();

            for (int i = 0; i < 3; i++)
            {
                Task <MiningResultDto> task = Task.Run(() => RentTimeOnLocalMiningServer("SecretToken", 4));
                localMiningTaskList.Add(task);
            }

            var localMiningArray = localMiningTaskList.ToArray();

            Task.WaitAll(localMiningArray);

            foreach (var task in localMiningArray)
            {
                result.MiningText += task.Result.MiningText + Environment.NewLine;
            }

            result.ElapsedSeconds = (DateTime.UtcNow - startTime).TotalSeconds;

            tcs.SetResult(result);
            return(tcs.Task);
        }
コード例 #2
0
        public async Task LaunchMiningMethodLocalAsync()
        {
            MiningResultDto result = await RentTimeOnLocalMiningServerTask("SecretToken", 5);

            Console.WriteLine($"mining result: {result.MiningText}");
            Console.WriteLine($"Elapsed seconds: {result.ElapsedSeconds:N}");
        }
コード例 #3
0
        public async Task <MiningResultDto> RentTimeOnMiningServerAsync(string authToken, int requestedAmount, CancellationToken cancellationToken)
        {
            if (!AuthorizeTheToken(authToken))
            {
                throw new Exception("Failed Authorization");
            }

            Thread.Sleep(1500);
            var result    = new MiningResultDto();
            var startTime = DateTime.UtcNow;
            var asyncTask = CallCoinServiceAsync(requestedAmount);

            if (cancellationToken.IsCancellationRequested)
            {
                cancellationToken.ThrowIfCancellationRequested();
            }

            var coinResult     = await asyncTask;
            var elapsedSeconds = (DateTime.UtcNow - startTime).TotalSeconds;

            result.ElapsedSeconds = elapsedSeconds;
            result.MiningText     = coinResult;

            return(result);
        }
コード例 #4
0
        public async Task LaunchMiningMethodAsync()
        {
            MiningResultDto result = await RentTimeOnMiningServerAsync("S3cr3tT0k3n", 4);

            System.Console.WriteLine($"Mining result: {result.MiningText}");
            System.Console.WriteLine($"Elapsed seconds: {result.ElapsedSeconds:N}");
        }
コード例 #5
0
        public async Task LaunchMiningMethodWithCancellationAsync()
        {
            /* The line new CancellationTokenSource(1000) puts a 1 second (1,000 millisecond) timeout on the Token that it creates.
             * There are other methods for requesting cancellation from the CancellationTokenSource.
             * You can use the cancellation methods from any thread that has access to the CancellationTokenSource
             * – which is essentially the parent object of the cancellation token you pass to a TAP method */
            var cts = new CancellationTokenSource(1000);

            Task <MiningResultDto> asyncTask = RentTimeOnMiningServerAsync("S3cr3tT0k3n", 4, cts.Token);

            try
            {
                MiningResultDto result = await asyncTask;
                System.Console.WriteLine($"Mining result: {result.MiningText}");
                System.Console.WriteLine($"Elapsed seconds: {result.ElapsedSeconds:N}");
                System.Console.WriteLine("End");
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                System.Console.WriteLine($"Task status:{asyncTask.Status}");
            }

            /* This is a fairly straightforward example of cancellation. There are a multitude of other ways to set up
             * methods that are cancelable and to request cancellation. These techniques can be used for both async and
             * parallel code.
             *
             * Further information can be found here: https://docs.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads */
        }
コード例 #6
0
        public MiningResultDto RentTimeOnLocalMiningServer(string authToken, int requestedIterations)
        {
            if (!AuthorizeTheToken(authToken))
            {
                throw new Exception("Failed Authorization");
            }

            var result     = new MiningResultDto();
            var startTime  = DateTime.UtcNow;
            var coinAmount = MineAsyncCoinsWithNthRoot(requestedIterations);

            result.ElapsedSeconds = (DateTime.UtcNow - startTime).TotalSeconds;
            result.MiningText     = $"You've got {coinAmount:N} AsyncCoin!";

            return(result);
        }
コード例 #7
0
        public async Task <MiningResultDto> RentTimeOnMiningServerAsync(string authToken, int requestedAmount)
        {
            if (!AuthorizeTheToken(authToken))
            {
                throw new Exception("Failed Authorization");
            }
            var result     = new MiningResultDto();
            var startTime  = DateTime.UtcNow;
            var coinResult = await CallCoinServiceAsync(requestedAmount);

            var elapsedSeconds = (DateTime.UtcNow - startTime).TotalSeconds;

            result.ElapsedSeconds = elapsedSeconds;
            result.MiningText     = coinResult;

            return(result);
        }
コード例 #8
0
        public async Task LaunchMiningMethodWithCancellationAsync()
        {
            var cts = new CancellationTokenSource(1000);
            Task <MiningResultDto> asyncTask = RentTimeOnMiningServerAsync("SecretToken", 4, cts.Token);

            try
            {
                MiningResultDto result = await asyncTask;
                Console.WriteLine($"mining result: {result.MiningText}");
                Console.WriteLine($"Elapsed seconds: {result.ElapsedSeconds:N}");
                Console.WriteLine("end");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine($"Task status: {asyncTask.Status}");
            }
        }
コード例 #9
0
        public async Task <MiningResultDto> RentTimeOnMiningServerAsync(string authToken, int requestedAmount)
        {
            /*  The class runs synchronous code for authorization and throws an error if authorization fails.
             *  TAP guidance: “An asynchronous method should only directly raise an exception to be thrown out of
             *  the MethodNameAsync call in response to a usage error. For all other errors, exceptions occurring
             *  during the execution of an asynchronous method should be assigned to the returned Task.” */
            if (!AuthorizeTheToken(authToken))
            {
                throw new Exception("Failed Authorization");
            }
            var result     = new MiningResultDto();
            var startTime  = DateTime.UtcNow;
            var coinResult = await CallCoinServiceAsync(requestedAmount);

            var elapsedSeconds = (DateTime.UtcNow - startTime).TotalSeconds;

            result.ElapsedSeconds = elapsedSeconds;
            result.MiningText     = coinResult;

            return(result);
        }
コード例 #10
0
        public Task <MiningResultDto> RentTimeOnLocalMiningServerTask(string authToken, int requestedIterations)
        {
            /* Parallel compute-bound method that runs multiple Tasks
             *
             * In this method there is a big difference with how the Task is created. Notice that you start with TaskCompletionSource<MiningResultDto>.
             * This object allows you more control of the content and behavior of a Task. By writing code then using the SetResult method, your method
             * creates a Task<T> and give it back to the consumer.
             *
             * Consuming code can simply await the completion of the task, or can use Task.Run to launch it on a background thread. */
            if (!AuthorizeTheToken(authToken))
            {
                throw new Exception("Failed Authorization");
            }

            var tcs      = new TaskCompletionSource <MiningResultDto>();
            var result   = new MiningResultDto();
            var starTime = DateTime.UtcNow;

            var localMiningTaskList = new List <Task <MiningResultDto> >();

            for (int i = 0; i < 3; i++)
            {
                Task <MiningResultDto> task = Task.Run(() => RentTimeOnLocalMiningServer("S3cr3tT0k3n", 5));
                localMiningTaskList.Add(task);
            }

            var localMiningArray = localMiningTaskList.ToArray();

            Task.WaitAll(localMiningArray);

            foreach (var task in localMiningArray)
            {
                result.MiningText += task.Result.MiningText + Environment.NewLine;
            }

            result.ElapsedSeconds = (DateTime.UtcNow - starTime).TotalSeconds;

            tcs.SetResult(result);
            return(tcs.Task);
        }