FieldWorkClient/ViewModel/Send/DownViewModel.cs

292 lines
8.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using HeBianGu.Base.WpfBase;
using HeBianGu.Service.Mvc;
using Hopetry.Models;
using Hopetry.Provider;
using Hopetry.Services;
using Newtonsoft.Json;
namespace Hopetry.ViewModel.Send;
[ViewModel("Down")]
public class DownViewModel : MvcViewModelBase
{
private readonly MinioService _minioService;
public RelayCommand<MinioDownloadTask> OpenDownItemFolder { get; set; }
private readonly ConcurrentQueue<MinioDownloadTask> _taskQueue = new();
private SemaphoreSlim _semaphore;
private CancellationTokenSource _processingCts = new();
public int count { get; set; }
private readonly ReaderWriterLockSlim _lock = new();
private Visibility _tab0Visibility;
public Visibility Tab0Visibility
{
get => _tab0Visibility;
set
{
_tab0Visibility = value;
RaisePropertyChanged();
}
}
private Visibility _tab1Visibility;
public Visibility Tab1Visibility
{
get => _tab1Visibility;
set
{
_tab1Visibility = value;
RaisePropertyChanged();
}
}
private int _tabIndex;
public int TabIndex
{
get => _tabIndex;
set
{
_tabIndex = value;
if (_tabIndex == 0)
{
Tab0Visibility = Visibility.Visible;
Tab1Visibility = Visibility.Hidden;
}
else if (_tabIndex == 1)
{
Tab0Visibility = Visibility.Hidden;
Tab1Visibility = Visibility.Visible;
}
RaisePropertyChanged();
}
}
/// <summary>
/// 全部任务动态标题
/// </summary>
private string _allTaskHeader;
public string AllTaskHeader
{
get => _allTaskHeader;
set
{
_allTaskHeader = value;
RaisePropertyChanged();
}
}
private string _runningTaskHeader;
public string RunningTaskHeader
{
get => _runningTaskHeader;
set
{
_runningTaskHeader = value;
RaisePropertyChanged();
}
}
private string _finishedTaskHeader;
public string FinishedTaskHeader
{
get => _finishedTaskHeader;
set
{
_finishedTaskHeader = value;
RaisePropertyChanged();
}
}
// 绑定属性
//public ObservableCollection<MinioDownloadTask> AllTasks { get; set; }
private ObservableCollection<MinioDownloadTask> _runningTasks;
public ObservableCollection<MinioDownloadTask> RunningTasks
{
get => _runningTasks;
set
{
_runningTasks = value;
RaisePropertyChanged(); // 触发INotifyPropertyChanged通知
}
}
private ObservableCollection<MinioDownloadTask> _finishedTasks;
public ObservableCollection<MinioDownloadTask> FinishedTasks
{
get => _finishedTasks;
set
{
_finishedTasks = value;
RaisePropertyChanged(); // 触发INotifyPropertyChanged通知
}
}
private int _maxConcurrent = 3;
public int MaxConcurrent
{
get => _maxConcurrent;
set
{
if (value < 1) value = 1;
if (_maxConcurrent == value) return;
_maxConcurrent = value;
//AdjustConcurrency();
RaisePropertyChanged();
}
}
public ICommand ClearFinishedCommand { get; }
/// <summary>
/// 构造函数
/// </summary>
/// <param name="minioService"></param>
public DownViewModel(MinioService minioService)
{
_minioService = minioService;
Console.WriteLine("初始化DownViewModel");
using var client = SqlSugarConfig.GetSqlSugarScope();
OpenDownItemFolder = new RelayCommand<MinioDownloadTask>(DoOpenDownItemFolder);
LoadFinishedTasks();
LoadRunningTasks();
ClearFinishedCommand = new CustomCommand(DoClearFinishedCommand);
// 启动任务处理线程
_semaphore = new SemaphoreSlim(MaxConcurrent);
new Thread(ProcessTasksLoop) { IsBackground = true }.Start();
}
private void DoClearFinishedCommand()
{
using var client = SqlSugarConfig.GetSqlSugarScope();
client.Deleteable<MinioDownloadTask>().Where(x => x.Status == "已完成").ExecuteCommand();
FinishedTasks.Clear();
FinishedTaskHeader = $"已完成0";
}
public void LoadRunningTasks()
{
using var client = SqlSugarConfig.GetSqlSugarScope();
var data = client.Ado
.SqlQuery<MinioDownloadTask>(
$"select * from download_task where status='下载中' or status='等待中' or status='已暂停' order by task_id desc");
RunningTasks = new ObservableCollection<MinioDownloadTask>(data);
RunningTaskHeader = $"下载中({RunningTasks.Count}";
}
public void LoadFinishedTasks()
{
using var client = SqlSugarConfig.GetSqlSugarScope();
var data = client.Ado
.SqlQuery<MinioDownloadTask>($"select * from download_task where status='已完成' order by datetime(finished_time) desc");
FinishedTasks = new ObservableCollection<MinioDownloadTask>(data);
FinishedTaskHeader = $"已完成({FinishedTasks.Count}";
}
private async void ProcessTasksLoop()
{
int c1 = 1;
while (!_processingCts.IsCancellationRequested)
{
if (_taskQueue.TryDequeue(out var task))
{
Console.WriteLine("存在可下载任务,正在申请许可...");
await _semaphore.WaitAsync();
Console.WriteLine("申请下载许可成功!马上开启下载");
// 启动新线程执行下载任务
// _ = Task.Run(() => ExecuteTaskAsync(task));
_ = ExecuteTaskAsync(task).ContinueWith(_ => _semaphore.Release());
}
// 无任务时,进入低功耗轮询
Thread.Sleep(500);
}
}
public void AddTask(string bucketName, string objectKey, string size)
{
var downDir = ViewModelLocator.SyncViewModel.SyncDir;
var task = new MinioDownloadTask(_minioService, bucketName, objectKey, downDir, size);
using var client = SqlSugarConfig.GetSqlSugarScope();
client.Insertable(task).ExecuteCommandIdentityIntoEntity();
LoadFinishedTasks();
LoadRunningTasks();
Console.WriteLine($"文件大小:{size} ");
_taskQueue.Enqueue(task);
}
private async Task ExecuteTaskAsync(MinioDownloadTask task)
{
try
{
await task.StartDownload();
LoadRunningTasks();
LoadFinishedTasks();
Console.WriteLine($"异步下载完成:{task.FileName}");
}
finally
{
}
}
private void AdjustConcurrency()
{
lock (_semaphore)
{
// 调整信号量容量
var delta = _maxConcurrent - _semaphore.CurrentCount;
if (delta > 0)
{
for (int i = 0; i < delta; i++)
{
_semaphore.Release();
}
}
}
}
public void DoOpenDownItemFolder(MinioDownloadTask para)
{
Console.WriteLine($"点击item值{JsonConvert.SerializeObject(para)}");
Process.Start("explorer.exe", para.FilePath);
}
public void DoCancelDownItem(MinioDownloadTask item)
{
Console.WriteLine("取消下载");
// todo 实现取消下载
}
public void DoPauseDownItem(MinioDownloadTask item)
{
Console.WriteLine("暂停下载");
// todo 实现暂停下载
}
protected override void Init()
{
}
protected override void Loaded(string args)
{
}
}