예제 #1
0
 public MultiBandAsyncSync(int bands)
 {
     Bands = new AsyncSync[bands];
     for (int i = 0; i < bands; i++)
     {
         Bands[i] = new AsyncSync();
     }
 }
예제 #2
0
        public async Task <int> RunAsync(int count = 1) // Assume that awaiting on this will take a long time
        {
            if (Executor == null)
            {
                TaskCompletionSource <Func <int, Task <int> > > exe = new TaskCompletionSource <Func <int, Task <int> > >();
                AsyncOperationsTask = Task.Factory.StartNew(() =>
                {
                    int n                             = 0;
                    AsyncSync sync                    = new AsyncSync();
                    AsyncWaiter flow_control          = new AsyncWaiter();
                    TaskCompletionSource <int> result = new TaskCompletionSource <int>();
                    Task <int> execute(int number)
                    {
                        return(sync.ExecuteAsync(async() =>
                        {
                            n = number;
                            await flow_control.PulseAsync(true);
                            try
                            {
                                number = await result.Task;
                            }
                            catch (Exception)
                            {
                                await Task.Yield();
                                result = new TaskCompletionSource <int>();
                                throw;
                            }

                            await Task.Yield();
                            result = new TaskCompletionSource <int>();
                            return number;
                        }));
                    }

                    exe.SetResult(execute);

                    while (n >= 0)
                    {
                        flow_control.Wait();

                        if (n > 0)
                        {
                            try
                            {
                                result.SetResult(Internal_Run(n));
                            }
                            catch (Exception e)
                            {
                                result.SetException(e);
                            }
                        }
                        else
                        {
                            result.SetResult(0);
                        }
                    }
                }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
                Interlocked.Exchange(ref Executor, await exe.Task)?.Invoke(-1);
                await Task.Yield();
            }

            return(await Executor(count));
        }