Fix calling schedule task cause deadlock (#1586)

This commit is contained in:
ReinforceZwei 2021-05-12 22:31:06 +08:00 committed by GitHub
parent 7723ed57ea
commit b15c3a8e46
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 55 additions and 6 deletions

View file

@ -701,13 +701,38 @@ namespace MinecraftClient
/// <param name="task">Task to run</param>
public object ScheduleTask(Delegate task)
{
var taskAndResult = new TaskWithResult(task);
lock (threadTasksLock)
if (!InvokeRequired())
{
threadTasks.Enqueue(taskAndResult);
return task.DynamicInvoke();
}
else
{
var taskAndResult = new TaskWithResult(task);
lock (threadTasksLock)
{
threadTasks.Enqueue(taskAndResult);
}
taskAndResult.Block();
return taskAndResult.Result;
}
}
/// <summary>
/// Check if calling thread is main thread or other thread
/// </summary>
/// <returns>True if calling thread is other thread</returns>
public bool InvokeRequired()
{
int callingThreadId = Thread.CurrentThread.ManagedThreadId;
if (handler != null)
{
return handler.GetNetReadThreadId() != callingThreadId;
}
else
{
// net read thread (main thread) not yet ready
return false;
}
taskAndResult.Block();
return taskAndResult.Result;
}
#region Management: Load/Unload ChatBots and Enable/Disable settings