Skip to content

Commit

Permalink
Load text data in another thread while keeping UI responsive
Browse files Browse the repository at this point in the history
  • Loading branch information
KyrietS committed Oct 20, 2024
1 parent 1e91db2 commit 6fd4202
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 10 deletions.
2 changes: 1 addition & 1 deletion src/LogAlligator.App/Controls/FileView.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ private async Task LoadFile()
ShowLoadingDialog();
await LoadData();
}
catch (TaskCanceledException)
catch (OperationCanceledException)
{
Log.Information("Loading data was canceled");
RequestRemovalFromView();
Expand Down
23 changes: 15 additions & 8 deletions src/LogAlligator.App/LineProvider/BufferedFileLineProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Threading;

namespace LogAlligator.App.LineProvider;

Expand All @@ -27,18 +28,24 @@ public async Task LoadData(Action<int> progressCallback, CancellationToken token
private async Task LoadLinesData(Action<int> progressCallback, CancellationToken token)
{
const FileOptions fileOptions = FileOptions.SequentialScan | FileOptions.Asynchronous;
await using var stream = new FileStream(path.LocalPath, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, fileOptions);
using var stream = new FileStream(path.LocalPath, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, fileOptions);
var reader = new StreamLineReader(stream, 65536);
int lineNumber = 1;

while (reader.ReadLine() is { } line) // TODO: Make Async
await Task.Run(() =>
{
_lines.Add((lineNumber, line.Begin, (int)line.Length));
lineNumber++;

if (_lines.Count % 100 == 0)
progressCallback(_lines.Count);
}
while (reader.ReadLine() is { } line)
{
_lines.Add((lineNumber, line.Begin, (int)line.Length));
lineNumber++;

if (_lines.Count % 1000 == 0)
{
token.ThrowIfCancellationRequested();
Dispatcher.UIThread.Post(() => progressCallback(_lines.Count));
}
}
}, token);

progressCallback(_lines.Count);
}
Expand Down
2 changes: 1 addition & 1 deletion src/LogAlligator.App/LineProvider/StreamLineReader.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.IO;

namespace LogAlligator.App.LineProvider;
Expand Down

0 comments on commit 6fd4202

Please sign in to comment.