Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fixed the bug that method CurrentTaskFinished was executed multiple times by multiple threads #1084

Merged
merged 5 commits into from
Sep 15, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 21 additions & 12 deletions src/Starward/Services/Download/InstallGameService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,8 @@ public void ClearState()

protected void StartTask(InstallGameState state)
{
if (_concurrentExecuteThreadCount > 0) return;

if (state is InstallGameState.Download)
{
if (InstallTask is InstallGameTask.HardLink)
Expand Down Expand Up @@ -713,10 +715,26 @@ protected void StartTask(InstallGameState state)
_finishBytes = 0;
}
State = state;
_cancellationTokenSource = new CancellationTokenSource();
for (int i = 0; i < Environment.ProcessorCount; i++)

_ = RunTasksAsync(); //不需要ConfigureAwait,因为返回值丢弃,且无需调用“.GetAwaiter().OnCompleted()”
return;

async Task RunTasksAsync()
{
_ = ExecuteTaskItemAsync(_cancellationTokenSource.Token).ConfigureAwait(false);
_cancellationTokenSource = new CancellationTokenSource();
var tasks = new Task[Environment.ProcessorCount];
for (int i = 0; i < Environment.ProcessorCount; i++)
{
tasks[i] = ExecuteTaskItemAsync(_cancellationTokenSource.Token);
}
try
{
await Task.WhenAll(tasks).ConfigureAwait(false);
}
finally
{
CurrentTaskFinished();
}
}
}

Expand Down Expand Up @@ -1106,11 +1124,6 @@ protected async Task ExecuteTaskItemAsync(CancellationToken cancellationToken =
try
{
Interlocked.Increment(ref _concurrentExecuteThreadCount);
if (_concurrentExecuteThreadCount > Environment.ProcessorCount)
{
return;
}

while (_installItemQueue.TryDequeue(out InstallGameItem? item))
{
try
Expand Down Expand Up @@ -1161,10 +1174,6 @@ protected async Task ExecuteTaskItemAsync(CancellationToken cancellationToken =
finally
{
Interlocked.Decrement(ref _concurrentExecuteThreadCount);
if (_concurrentExecuteThreadCount == 0)
{
CurrentTaskFinished();
}
}
}

Expand Down
Loading