public async Task <int> Add(string title, Func <CancellationToken, bool> request) { var newaction = new BulkActionInternal() { title = title, requestTime = DateTime.Now, request = request, cts = new CancellationTokenSource(), }; return(await Task <int> .Run(() => { int newid; bool isFirst = false; lock (mutex) { newid = ++idalloc; newaction.id = newid; newaction.state = BulkAction.State.Wait; actions.Add(newaction); isFirst = actions.Where(a => a.state == BulkAction.State.Wait).Count() == 1; } if (isFirst) { arevent.Set(); } return newid; })); }
public void Onthread() { while (true) { arevent.WaitOne(); BulkActionInternal running = null; bool isComplate = false; while (true) { lock (mutex) { if (running != null) { running.state = isComplate ? BulkAction.State.Complete : BulkAction.State.Canceled; running.completeTime = DateTime.Now; running = null; isComplate = false; RunningActionID = 0; var compCount = actions.Where(a => a.state.IsFinished()).Count(); if (compCount > MaxCompleteItemCount) { actions.RemoveRange(0, compCount - MaxCompleteItemCount); } } if (markedShutdown) { break; } running = actions.Where(a => a.state == BulkAction.State.Wait).FirstOrDefault(); if (running == null) { break; } running.state = BulkAction.State.Running; RunningActionID = running.id; } try { isComplate = running.request(running.cts.Token); } catch (Exception e) { //running.request.IsCanceled(); } } if (markedShutdown) { break; } } }