You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Zero/ZeroLevel/Services/Network/FileTransfer/BaseFileTransfer.cs

73 lines
2.4 KiB

6 years ago
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Threading;
using ZeroLevel.Services.Pools;
6 years ago
namespace ZeroLevel.Network.FileTransfer
6 years ago
{
public abstract class BaseFileTransfer
{
private readonly FileReceiver _receiver;
internal FileReceiver Receiver => _receiver;
private ObjectPool<FileTransferTask> _taskPool = new ObjectPool<FileTransferTask>(() => new FileTransferTask(), 100);
private BlockingCollection<FileTransferTask> _tasks = new BlockingCollection<FileTransferTask>();
private readonly Thread _uploadFileThread;
5 years ago
internal BaseFileTransfer(string baseFolder)
6 years ago
{
_receiver = new FileReceiver(baseFolder);
_uploadFileThread = new Thread(UploadFileProcessing);
_uploadFileThread.IsBackground = true;
_uploadFileThread.Start();
}
protected void PushTransferTask(string filePath, Action<string> completeHandler = null, Action<string, string> errorHandler = null, ExClient client = null)
6 years ago
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (false == File.Exists(filePath))
{
throw new FileNotFoundException(filePath);
}
var task = _taskPool.Allocate();
task.CompletedHandler = completeHandler;
task.ErrorHandler = errorHandler;
task.FilePath = filePath;
task.Client = client;
_tasks.Add(task);
}
private void UploadFileProcessing()
{
while (true)
{
var task = _tasks.Take();
try
{
ExecuteSendFile(GetReaderFor(task.FilePath), task);
task.CompletedHandler?.Invoke(task.FilePath);
}
catch (Exception ex)
{
task.ErrorHandler?.Invoke(task.FilePath, ex.ToString());
}
finally
{
_taskPool.Free(task);
}
}
}
internal abstract void ExecuteSendFile(FileReader reader, FileTransferTask task);
private FileReader GetReaderFor(string filePath)
{
return new FileReader(filePath);
}
}
}

Powered by TurnKey Linux.