Skip to content

Commit

Permalink
Convert BackgroundWorker into Task
Browse files Browse the repository at this point in the history
  • Loading branch information
ied206 committed Sep 1, 2018
1 parent 8429dad commit 7d15795
Show file tree
Hide file tree
Showing 11 changed files with 473 additions and 470 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.

# Joveler-specific Resoures
BinaryRelease/
res/
PEBakery/Core/Parser/.antlr
PEBakery.Tests/Samples/WorkBench/TestSuite/Dest/
Expand Down
2 changes: 1 addition & 1 deletion PEBakery.Tests/TestSetup.cs
Expand Up @@ -20,7 +20,7 @@ public static void PrepareTests(TestContext ctx)
projects.Load(null);

// Should be only one project named TestSuite
EngineTests.Project = projects.Projects[0];
EngineTests.Project = projects.ProjectList[0];

// Init NativeAssembly
NativeGlobalInit();
Expand Down
12 changes: 9 additions & 3 deletions PEBakery/Core/Commands/CommandInterface.cs
Expand Up @@ -125,10 +125,16 @@ public static List<LogInfo> VisibleOp(EngineState s, CodeCommand cmd)
CodeInfo_Visible info = subCmd.Info.Cast<CodeInfo_Visible>();

string visibilityStr = StringEscaper.Preprocess(s, info.Visibility);
bool visibility = false;
if (visibilityStr.Equals("True", StringComparison.OrdinalIgnoreCase))
Debug.Assert(visibilityStr != null, $"{nameof(visibilityStr)} != null");

bool visibility;
if (visibilityStr.Equals("1", StringComparison.Ordinal) ||
visibilityStr.Equals("True", StringComparison.OrdinalIgnoreCase))
visibility = true;
else if (!visibilityStr.Equals("False", StringComparison.OrdinalIgnoreCase))
else if (visibilityStr.Equals("0", StringComparison.Ordinal) ||
visibilityStr.Equals("False", StringComparison.OrdinalIgnoreCase))
visibility = false;
else
return LogInfo.LogErrorMessage(logs, $"Invalid boolean value [{visibilityStr}]");

prepArgs.Add((info.UIControlKey, visibility, subCmd));
Expand Down
14 changes: 7 additions & 7 deletions PEBakery/Core/Commands/CommandSystem.cs
Expand Up @@ -35,6 +35,7 @@
using System.Security.Principal;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using PEBakery.WPF;
using PEBakery.Helper;

Expand Down Expand Up @@ -214,13 +215,11 @@ public static List<LogInfo> SystemCmd(EngineState s, CodeCommand cmd)
{
Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo), "Invalid CodeInfo");

AutoResetEvent resetEvent = null;
Application.Current?.Dispatcher.Invoke(() =>
{
MainWindow w = Application.Current.MainWindow as MainWindow;
resetEvent = w?.StartRefreshScriptWorker();
w?.StartRefreshScript().Wait();
});
resetEvent?.WaitOne();

logs.Add(new LogInfo(LogState.Success, $"Rerendered script [{cmd.Addr.Script.Title}]"));
}
Expand All @@ -231,13 +230,14 @@ public static List<LogInfo> SystemCmd(EngineState s, CodeCommand cmd)
Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo), "Invalid CodeInfo");

// Refresh Project
AutoResetEvent resetEvent = null;
Task scriptLoadTask = Task.CompletedTask;
Application.Current?.Dispatcher.Invoke(() =>
{
MainWindow w = Application.Current.MainWindow as MainWindow;
resetEvent = w?.StartLoadWorker(true);
if (!(Application.Current.MainWindow is MainWindow w))
return;
scriptLoadTask = w.StartLoadingProjects(true);
});
resetEvent?.WaitOne();
scriptLoadTask.Wait();

logs.Add(new LogInfo(LogState.Success, $"Reload project [{cmd.Addr.Script.Project.ProjectName}]"));
}
Expand Down
6 changes: 3 additions & 3 deletions PEBakery/Core/Engine.cs
Expand Up @@ -1034,14 +1034,14 @@ public enum LogMode
/// - Medium performance impact
/// - Write to database when script is finised
/// </summary>
PartDelay,
PartDefer,
/// <summary>
/// For interface button
/// - Minimize performance impact
/// - Disable trivial LogWindow event
/// - Write to database after bulid is finished
/// </summary>
FullDelay,
FullDefer,
}
#endregion

Expand Down Expand Up @@ -1177,7 +1177,7 @@ public void SetOptions(SettingViewModel m)
{
CustomUserAgent = m.General_UseCustomUserAgent ? m.General_CustomUserAgent : null;

LogMode = m.Log_DeferredLogging ? LogMode.PartDelay : LogMode.NoDelay;
LogMode = m.Log_DeferredLogging ? LogMode.PartDefer : LogMode.NoDelay;

CompatDirCopyBug = m.Compat_AsteriskBugDirCopy;
CompatFileRenameCanMoveDir = m.Compat_FileRenameCanMoveDir;
Expand Down
36 changes: 18 additions & 18 deletions PEBakery/Core/Logger.cs
Expand Up @@ -334,7 +334,7 @@ public DeferredLogging(bool fullDelayed)
/// <returns>Real BuildId after written to database</returns>
public int FlushFullDeferred(EngineState s)
{
if (s.LogMode != LogMode.FullDelay)
if (s.LogMode != LogMode.FullDefer)
return s.BuildId;

Debug.Assert(BuildInfo != null, "Internal Logic Error at DelayedLogging");
Expand Down Expand Up @@ -472,11 +472,11 @@ public int Flush(EngineState s)
{
switch (s.LogMode)
{
case LogMode.PartDelay:
case LogMode.PartDefer:
Db.InsertAll(_deferred.BuildLogPool);
_deferred.BuildLogPool.Clear();
break;
case LogMode.FullDelay:
case LogMode.FullDefer:
return _deferred.FlushFullDeferred(s);
}
return s.BuildId;
Expand All @@ -498,18 +498,18 @@ public int BuildInit(EngineState s, string name)

switch (s.LogMode)
{
case LogMode.PartDelay:
case LogMode.PartDefer:
_deferred = new DeferredLogging(false);
break;
case LogMode.FullDelay:
case LogMode.FullDefer:
_deferred = new DeferredLogging(true);

dbBuild.Id = -1;
_deferred.BuildInfo = dbBuild;
break;
}

if (s.LogMode != LogMode.FullDelay)
if (s.LogMode != LogMode.FullDefer)
{
Db.Insert(dbBuild);

Expand Down Expand Up @@ -537,12 +537,12 @@ public int BuildInit(EngineState s, string name)
varLogs.Add(dbVar);

// Fire Event
if (s.LogMode != LogMode.FullDelay)
if (s.LogMode != LogMode.FullDefer)
VariableUpdated?.Invoke(this, new VariableUpdateEventArgs(dbVar));
}
}

if (s.LogMode == LogMode.FullDelay)
if (s.LogMode == LogMode.FullDefer)
_deferred.VariablePool.AddRange(varLogs);
else
Db.InsertAll(varLogs);
Expand All @@ -566,7 +566,7 @@ public void BuildFinish(EngineState s)

switch (s.LogMode)
{
case LogMode.PartDelay:
case LogMode.PartDefer:
Flush(s);
Db.Update(dbBuild);
break;
Expand Down Expand Up @@ -601,7 +601,7 @@ public int BuildScriptInit(EngineState s, Script sc, int order, bool prepareBuil
dbScript.Version = "0";
}

if (s.LogMode == LogMode.FullDelay)
if (s.LogMode == LogMode.FullDefer)
{
_deferred.CurrentScriptId -= 1;
dbScript.Id = _deferred.CurrentScriptId;
Expand All @@ -626,7 +626,7 @@ public void BuildScriptFinish(EngineState s, Dictionary<string, string> localVar
if (s.DisableLogger)
return;

if (s.LogMode == LogMode.PartDelay)
if (s.LogMode == LogMode.PartDefer)
{
Db.InsertAll(_deferred.BuildLogPool);
_deferred.BuildLogPool.Clear();
Expand Down Expand Up @@ -661,21 +661,21 @@ public void BuildScriptFinish(EngineState s, Dictionary<string, string> localVar
varLogs.Add(dbVar);

// Fire Event
if (s.LogMode != LogMode.FullDelay)
if (s.LogMode != LogMode.FullDefer)
VariableUpdated?.Invoke(this, new VariableUpdateEventArgs(dbVar));
}

if (s.LogMode == LogMode.FullDelay)
if (s.LogMode == LogMode.FullDefer)
_deferred.VariablePool.AddRange(varLogs);
else
Db.InsertAll(varLogs);
}

if (s.LogMode != LogMode.FullDelay)
if (s.LogMode != LogMode.FullDefer)
Db.Update(dbScript);

// Fire Event
if (s.LogMode == LogMode.PartDelay)
if (s.LogMode == LogMode.PartDefer)
ScriptUpdated?.Invoke(this, new ScriptUpdateEventArgs(dbScript));
}

Expand All @@ -699,7 +699,7 @@ public int BuildRefScriptWrite(EngineState s, Script sc)
ElapsedMilliSec = 0,
};

if (s.LogMode == LogMode.FullDelay)
if (s.LogMode == LogMode.FullDefer)
{
_deferred.CurrentScriptId -= 1;
dbScript.Id = _deferred.CurrentScriptId;
Expand Down Expand Up @@ -729,8 +729,8 @@ private void InternalBuildWrite(EngineState s, DB_BuildLog dbCode)
{
switch (s.LogMode)
{
case LogMode.FullDelay:
case LogMode.PartDelay:
case LogMode.FullDefer:
case LogMode.PartDefer:
_deferred.BuildLogPool.Add(dbCode);
break;
case LogMode.NoDelay:
Expand Down
44 changes: 27 additions & 17 deletions PEBakery/Core/Project.cs
Expand Up @@ -65,9 +65,9 @@ public class ProjectCollection : IReadOnlyCollection<Project>

#region Properties
public string ProjectRoot { get; }
public List<Project> Projects => _projectDict.Values.OrderBy(x => x.ProjectName).ToList();
public List<Project> ProjectList => _projectDict.Values.OrderBy(x => x.ProjectName).ToList();
public List<string> ProjectNames => _projectDict.Keys.OrderBy(x => x).ToList();
public Project this[int i] => Projects[i];
public Project this[int i] => ProjectList[i];
public int Count => _projectDict.Count;
#endregion

Expand Down Expand Up @@ -271,7 +271,17 @@ private List<(string RealPath, string TreePath, bool IsDir)> GetDirLinks(string
#endregion

#region Load, LoadLinks
public List<LogInfo> Load(BackgroundWorker worker)
public enum LoadReport
{
None,
LoadingCache,
Stage1,
Stage1Cached,
Stage2,
Stage2Cached,
}

public List<LogInfo> Load(IProgress<(LoadReport Type, string Path)> progress)
{
List<LogInfo> logs = new List<LogInfo>(32);
try
Expand All @@ -281,7 +291,7 @@ public List<LogInfo> Load(BackgroundWorker worker)
Project project = new Project(_baseDir, key);

// Load scripts
List<LogInfo> projLogs = project.Load(_scriptPathDict[key], _dirLinkPathDict[key], _scriptCache, worker);
List<LogInfo> projLogs = project.Load(_scriptPathDict[key], _dirLinkPathDict[key], _scriptCache, progress);
logs.AddRange(projLogs);

// Add Project.Scripts to ProjectCollections.Scripts
Expand All @@ -291,7 +301,7 @@ public List<LogInfo> Load(BackgroundWorker worker)
}

// Populate *.link scripts
List<LogInfo> linkLogs = LoadLinks(worker);
List<LogInfo> linkLogs = LoadLinks(progress);
logs.AddRange(linkLogs);

// PostLoad scripts
Expand All @@ -310,7 +320,7 @@ public List<LogInfo> Load(BackgroundWorker worker)
return logs;
}

private List<LogInfo> LoadLinks(BackgroundWorker worker)
private List<LogInfo> LoadLinks(IProgress<(LoadReport Type, string Path)> progress)
{
List<LogInfo> logs = new List<LogInfo>(32);
List<int> removeIdxs = new List<int>();
Expand All @@ -319,7 +329,7 @@ private List<LogInfo> LoadLinks(BackgroundWorker worker)
DB_ScriptCache[] cacheDb = null;
if (_scriptCache != null)
{
worker?.ReportProgress(-1);
progress?.Report((LoadReport.LoadingCache, null));
cacheDb = _scriptCache.Table<DB_ScriptCache>().ToArray();
}

Expand All @@ -330,7 +340,7 @@ private List<LogInfo> LoadLinks(BackgroundWorker worker)
{
Script link = null;
bool valid = false;
int cached = 2;
LoadReport cached = LoadReport.Stage2;
try
{
do
Expand Down Expand Up @@ -366,7 +376,7 @@ private List<LogInfo> LoadLinks(BackgroundWorker worker)
{
link.Project = sc.Project;
link.IsDirLink = false;
cached = 3;
cached = LoadReport.Stage2Cached;
}
}
catch { link = null; }
Expand Down Expand Up @@ -405,13 +415,13 @@ private List<LogInfo> LoadLinks(BackgroundWorker worker)
{
sc.LinkLoaded = true;
sc.Link = link;
worker?.ReportProgress(cached, Path.GetDirectoryName(sc.TreePath));
progress?.Report((cached, Path.GetDirectoryName(sc.TreePath)));
}
else // Error
{
int idx = _allProjectScripts.IndexOf(sc);
removeIdxs.Add(idx);
worker?.ReportProgress(cached);
progress?.Report((cached, null));
}
});

Expand Down Expand Up @@ -488,7 +498,7 @@ public ScriptParseInfo(string realPath, string treePath, bool isDir, bool isDirL
List<(string Path, bool IsDir)> allScriptPathList,
List<(string RealPath, string TreePath, bool IsDir)> allDirLinkPathList,
ScriptCache scriptCache,
BackgroundWorker worker)
IProgress<(ProjectCollection.LoadReport Type, string Path)> progress)
{
List<LogInfo> logs = new List<LogInfo>(32);

Expand All @@ -499,7 +509,7 @@ public ScriptParseInfo(string realPath, string treePath, bool isDir, bool isDirL
DB_ScriptCache[] cacheDb = null;
if (scriptCache != null)
{
worker?.ReportProgress(-1);
progress?.Report((ProjectCollection.LoadReport.LoadingCache, null));
cacheDb = scriptCache.Table<DB_ScriptCache>().ToArray();
}

Expand All @@ -515,7 +525,7 @@ public ScriptParseInfo(string realPath, string treePath, bool isDir, bool isDirL
Debug.Assert(spi.RealPath != null, "Internal Logic Error at Project.Load");
Debug.Assert(spi.TreePath != null, "Internal Logic Error at Project.Load");
int cached = 0;
ProjectCollection.LoadReport cached = ProjectCollection.LoadReport.Stage1;
Script sc = null;
try
{
Expand Down Expand Up @@ -545,7 +555,7 @@ public ScriptParseInfo(string realPath, string treePath, bool isDir, bool isDirL
{
sc.Project = this;
sc.IsDirLink = spi.IsDirLink;
cached = 1;
cached = ProjectCollection.LoadReport.Stage1Cached;
}
}
catch { sc = null; } // Cache Error
Expand Down Expand Up @@ -579,12 +589,12 @@ public ScriptParseInfo(string realPath, string treePath, bool isDir, bool isDirL
listLock.ExitWriteLock();
}
worker?.ReportProgress(cached, Path.GetDirectoryName(sc.TreePath));
progress?.Report((cached, Path.GetDirectoryName(sc.TreePath)));
}
catch (Exception e)
{
logs.Add(new LogInfo(LogState.Error, Logger.LogExceptionMessage(e)));
worker?.ReportProgress(cached);
progress?.Report((cached, null));
}
});

Expand Down

0 comments on commit 7d15795

Please sign in to comment.