bool TryRunTask(DataTaskComplited OnComplete, IDataLoadTaskData data, SortedDictionary<int, List<IDataLoader>> srvAv) { var sid = data.ServerID; List<IDataLoader> ldrs; if (srvAv.TryGetValue(sid, out ldrs)) { var ldr = FindBestLoader(sid, ldrs); if (ldr != null) { StartDownloadTask(OnComplete, ldr, data); if(ldr.CheckStatusFor(sid) == DataLoaderStatus.Busy) ldrs.Remove(ldr); if (ldrs.Count == 0) { srvAv.Remove(sid); return true; } } } return false; }
void StartDownloadTask(DataTaskComplited OnComplete, IDataLoader loader, IDataLoadTaskData data) { var item = new DownloadTaskItem(data, loader); lock (_Tasks) { _Tasks.Add(item); } Task.Factory.StartNew(() => { switch (StartDownload(OnComplete, loader, data)) { case DataLoadingResult.Suspended: case DataLoadingResult.LoaderErr: var task = new Tuple<IDataLoadTaskData, DataTaskComplited>(data, OnComplete); lock (PrivateTasks) { PrivateTasks.Add(task); _ready.Set(); } break; } lock (_Tasks) { _Tasks.Remove(item); } }, item.Data.Token); }
DataLoadingResult StartDownload(DataTaskComplited OnComplete, IDataLoader loader, IDataLoadTaskData data) { DataLoadingResult result = DataLoadingResult.LoaderErr; var ts = CancellationTokenSource.CreateLinkedTokenSource(Core.Core.globalCTS.Token, data.Token); foreach (var uri in data.Uri) { if (ts.IsCancellationRequested) return DataLoadingResult.Cancelled; result = loader.LoadMethod(uri, ts.Token, data.OnProcessCallback, 1024); if (result == DataLoadingResult.Ok || result == DataLoadingResult.Suspended || result == DataLoadingResult.Cancelled) break; } if (OnComplete != null && result != DataLoadingResult.Suspended && result != DataLoadingResult.LoaderErr && !Core.Core.globalCTS.IsCancellationRequested) OnComplete(data, result == DataLoadingResult.Ok ? TaskResult.Completed : result == DataLoadingResult.Cancelled ? TaskResult.Cancelled : TaskResult.Error); return result; }
public Task<TaskResult> GetData(IDataLoadTaskData Data) { var result = TaskResult.Cancelled; ManualResetEvent cmpl = new ManualResetEvent(false); DataTaskComplited oncmpl = (d, r) => { result = r; cmpl.Set(); }; var task = new Tuple<IDataLoadTaskData, DataTaskComplited>(Data, oncmpl); lock (PrivateTasks) { PrivateTasks.Add(task); Data.Token.Register(() => { lock (PrivateTasks) { cmpl.Set(); PrivateTasks.Remove(task); } }); } _ready.Set(); return Task.Factory.StartNew(() => { cmpl.WaitOne(); return result; }, Data.Token); }
public DownloadTaskItem(IDataLoadTaskData Data, IDataLoader Loader) { _Data = Data; _Loader = Loader; }