Code Review
This commit is contained in:
1 parent
be6336f548
commit
9158a69b62
11 files changed
+103
-65
No files matched your search
@@ -6,59 +6,59 @@
|
||||
public class ConcurrentList<T> : IList<T>, IList, IEnumerable, IEnumerable<T> {
|
||||
|
||||
private readonly List<T> _items = [];
|
||||
public readonly object syncLock = new();
|
||||
|
||||
// 构造函数
|
||||
public ConcurrentList() { }
|
||||
public ConcurrentList(IEnumerable<T> data) => _items = new(data);
|
||||
public static implicit operator ConcurrentList<T>(List<T> data) => new(data);
|
||||
public static implicit operator List<T>(ConcurrentList<T> data) { lock (data.syncLock) { return new(data._items); } }
|
||||
public static implicit operator List<T>(ConcurrentList<T> data) { lock (data._syncLock) { return new(data._items); } }
|
||||
|
||||
// 枚举器
|
||||
/// <summary>
|
||||
/// 返回此列表的副本。
|
||||
/// </summary>
|
||||
public IEnumerator<T> GetEnumerator() { lock (syncLock) return _items.ToList().GetEnumerator(); }
|
||||
public IEnumerator<T> GetEnumerator() { lock (_syncLock) return _items.ToList().GetEnumerator(); }
|
||||
/// <summary>
|
||||
/// 返回此列表的副本。
|
||||
/// </summary>
|
||||
IEnumerator IEnumerable.GetEnumerator() { lock (syncLock) return _items.ToList().GetEnumerator(); }
|
||||
IEnumerator IEnumerable.GetEnumerator() { lock (_syncLock) return _items.ToList().GetEnumerator(); }
|
||||
|
||||
// 成员
|
||||
public int Count { get { lock (syncLock) { return _items.Count; } } }
|
||||
public int Count { get { lock (_syncLock) { return _items.Count; } } }
|
||||
public bool IsReadOnly => false;
|
||||
bool IList.IsFixedSize => false;
|
||||
bool ICollection.IsSynchronized => true;
|
||||
object ICollection.SyncRoot => syncLock;
|
||||
private readonly object _syncLock = new();
|
||||
object ICollection.SyncRoot => _syncLock;
|
||||
|
||||
public T this[int index] {
|
||||
get { lock (syncLock) { return _items[index]; } }
|
||||
set { lock (syncLock) { _items[index] = value; } }
|
||||
get { lock (_syncLock) { return _items[index]; } }
|
||||
set { lock (_syncLock) { _items[index] = value; } }
|
||||
}
|
||||
object? IList.this[int index] {
|
||||
get => this[index];
|
||||
set { lock (syncLock) { _items[index] = (T) value!; } }
|
||||
set { lock (_syncLock) { _items[index] = (T) value!; } }
|
||||
}
|
||||
|
||||
public void Add(T item) { lock (syncLock) { _items.Add(item); } }
|
||||
int IList.Add(object? value) { lock (syncLock) { _items.Add((T) value!); return _items.Count - 1; } }
|
||||
public void Add(T item) { lock (_syncLock) { _items.Add(item); } }
|
||||
int IList.Add(object? value) { lock (_syncLock) { _items.Add((T) value!); return _items.Count - 1; } }
|
||||
|
||||
public void Insert(int index, T item) { lock (syncLock) { _items.Insert(index, item); } }
|
||||
void IList.Insert(int index, object? value) { lock (syncLock) { _items.Insert(index, (T) value!); } }
|
||||
public void Insert(int index, T item) { lock (_syncLock) { _items.Insert(index, item); } }
|
||||
void IList.Insert(int index, object? value) { lock (_syncLock) { _items.Insert(index, (T) value!); } }
|
||||
|
||||
public bool Remove(T item) { lock (syncLock) { return _items.Remove(item); } }
|
||||
void IList.Remove(object? value) { lock (syncLock) { if (value is T t) _items.Remove(t); } }
|
||||
public bool Remove(T item) { lock (_syncLock) { return _items.Remove(item); } }
|
||||
void IList.Remove(object? value) { lock (_syncLock) { if (value is T t) _items.Remove(t); } }
|
||||
|
||||
public void RemoveAt(int index) { lock (syncLock) { _items.RemoveAt(index); } }
|
||||
public void Clear() { lock (syncLock) { _items.Clear(); } }
|
||||
public void RemoveAt(int index) { lock (_syncLock) { _items.RemoveAt(index); } }
|
||||
public void Clear() { lock (_syncLock) { _items.Clear(); } }
|
||||
|
||||
public bool Contains(T item) { lock (syncLock) { return _items.Contains(item); } }
|
||||
bool IList.Contains(object? value) { lock (syncLock) { return value is T t && _items.Contains(t); } }
|
||||
public bool Contains(T item) { lock (_syncLock) { return _items.Contains(item); } }
|
||||
bool IList.Contains(object? value) { lock (_syncLock) { return value is T t && _items.Contains(t); } }
|
||||
|
||||
public int IndexOf(T item) { lock (syncLock) { return _items.IndexOf(item); } }
|
||||
int IList.IndexOf(object? value) { lock (syncLock) { return value is T t ? _items.IndexOf(t) : -1; } }
|
||||
public int IndexOf(T item) { lock (_syncLock) { return _items.IndexOf(item); } }
|
||||
int IList.IndexOf(object? value) { lock (_syncLock) { return value is T t ? _items.IndexOf(t) : -1; } }
|
||||
|
||||
public void CopyTo(T[] array, int arrayIndex) { lock (syncLock) { _items.CopyTo(array, arrayIndex); } }
|
||||
void ICollection.CopyTo(Array array, int index) { lock (syncLock) { ((ICollection) _items).CopyTo(array, index); } }
|
||||
public void CopyTo(T[] array, int arrayIndex) { lock (_syncLock) { _items.CopyTo(array, arrayIndex); } }
|
||||
void ICollection.CopyTo(Array array, int index) { lock (_syncLock) { ((ICollection) _items).CopyTo(array, index); } }
|
||||
|
||||
}
|
||||
+33
-11
@@ -91,6 +91,20 @@ public static class Logger {
|
||||
=> Log(ex, message, LogLevel.Warning, behavior, filePath);
|
||||
public static void Error(Exception ex, string? message = null, LogBehavior behavior = LogBehavior.AlertThenFeedback, [CallerFilePath] string filePath = "")
|
||||
=> Log(ex, message, LogLevel.Error, behavior, filePath);
|
||||
|
||||
/// <summary>
|
||||
/// 在不调用 Logger 的情况下,将信息直接发送到输出窗口。
|
||||
/// </summary>
|
||||
[Conditional("DEBUG")]
|
||||
public static void SendToDebug(string message, LogLevel level = LogLevel.Error, [CallerFilePath] string filePath = "")
|
||||
=> Debug.WriteLine($"{BaseLogger.GetLogPrefix(level, filePath)}{message}");
|
||||
/// <summary>
|
||||
/// 在不调用 Logger 的情况下,将信息直接发送到输出窗口。
|
||||
/// </summary>
|
||||
[Conditional("DEBUG")]
|
||||
public static void SendToDebug(Exception ex, string? message = null, LogLevel level = LogLevel.Error, [CallerFilePath] string filePath = "")
|
||||
=> Debug.WriteLine($"{BaseLogger.GetLogPrefix(level, filePath)}{(message is null ? "" : $"{message}:")}{ex.GetDisplay(true)}");
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -111,7 +125,9 @@ public class BaseLogger {
|
||||
var formattedMessage = Format(message, level, filePath, null);
|
||||
Output(formattedMessage, level);
|
||||
HandleBehavior(message, formattedMessage, behavior, null);
|
||||
} catch {}
|
||||
} catch (Exception logEx) {
|
||||
Logger.SendToDebug(logEx, "打印日志失败");
|
||||
}
|
||||
}
|
||||
public virtual void Log(Exception ex, string? message, LogLevel level, LogBehavior behavior, string filePath) {
|
||||
if (MinLevel > level) return;
|
||||
@@ -121,19 +137,23 @@ public class BaseLogger {
|
||||
formattedMessage = Format(formattedMessage, level, filePath, ex);
|
||||
Output(formattedMessage, level);
|
||||
HandleBehavior(message, formattedMessage, behavior, ex);
|
||||
} catch { }
|
||||
} catch (Exception logEx) {
|
||||
Logger.SendToDebug(logEx, "打印日志失败");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 格式化日志文本。
|
||||
/// </summary>
|
||||
protected virtual string Format(string text, LogLevel level, string filePath, Exception? ex) {
|
||||
string prefix = $"{DateTime.Now:HH':'mm':'ss'.'fff} {level.ToString().First()} {(Thread.CurrentThread.Name is null ? "" : $"<{Thread.CurrentThread.Name}> ")}[{Path.GetFileName(filePath).BeforeFirst(".")}] ";
|
||||
string prefix = GetLogPrefix(level, filePath);
|
||||
return text
|
||||
.ReplaceLineEndings("\n", mergeMultiple: true).Split(['\n'], StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(t => prefix + t)
|
||||
.Join("\r\n");
|
||||
}
|
||||
public static string GetLogPrefix(LogLevel level, string filePath)
|
||||
=> $"{DateTime.Now:HH':'mm':'ss'.'fff} {level.ToString().First()} {(Thread.CurrentThread.Name is null ? "" : $"<{Thread.CurrentThread.Name}> ")}[{Path.GetFileName(filePath).BeforeFirst(".")}] ";
|
||||
|
||||
/// <summary>
|
||||
/// 输出格式化后的日志文本。
|
||||
@@ -159,7 +179,7 @@ public class FileLogger : BaseLogger, IDisposable {
|
||||
/// <inheritdoc/>
|
||||
protected override void Output(string formattedText, LogLevel level) {
|
||||
base.Output(formattedText, level);
|
||||
if (!writerAvaliable && queue.Count >= 100) return; // 在 writer 就绪前,最多缓存 100 条日志
|
||||
if (!writerAvailable && queue.Count >= 100) return; // 在 writer 就绪前,最多缓存 100 条日志
|
||||
queue.Enqueue(formattedText);
|
||||
queuedEvent.Set();
|
||||
}
|
||||
@@ -167,7 +187,7 @@ public class FileLogger : BaseLogger, IDisposable {
|
||||
private readonly ConcurrentQueue<string> queue = new();
|
||||
private readonly AutoResetEvent queuedEvent = new(false);
|
||||
private StreamWriter? writer;
|
||||
private volatile bool writerAvaliable = false;
|
||||
private volatile bool writerAvailable = false;
|
||||
|
||||
/// <summary>
|
||||
/// 将日志立即写入文件。
|
||||
@@ -175,10 +195,12 @@ public class FileLogger : BaseLogger, IDisposable {
|
||||
/// </summary>
|
||||
public void Flush() {
|
||||
try {
|
||||
if (writer is null || !writerAvaliable) return;
|
||||
lock (flushLock)
|
||||
if (writer is null || !writerAvailable) return;
|
||||
lock (flushLock)
|
||||
while (queue.TryDequeue(out string line)) writer.WriteLine(line); // writer 指定了 AutoFlush
|
||||
} catch { }
|
||||
} catch (Exception logEx) {
|
||||
Logger.SendToDebug(logEx, "写入日志失败");
|
||||
}
|
||||
}
|
||||
private readonly object flushLock = new();
|
||||
|
||||
@@ -206,7 +228,7 @@ public class FileLogger : BaseLogger, IDisposable {
|
||||
// 写入新日志文件
|
||||
try {
|
||||
writer = new StreamWriter(PathUtils.WithLongPath(Path.Combine(logFolder, $"{fileNamePrefix}1{fileNameSuffix}")), append: true) { AutoFlush = true };
|
||||
writerAvaliable = true;
|
||||
writerAvailable = true;
|
||||
Logger.Info("日志初始化成功");
|
||||
while (true) {
|
||||
queuedEvent.WaitOne();
|
||||
@@ -214,14 +236,14 @@ public class FileLogger : BaseLogger, IDisposable {
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
Logger.Warning(ex, "写入日志文件失败", LogBehavior.Toast);
|
||||
writerAvaliable = false;
|
||||
writerAvailable = false;
|
||||
}
|
||||
}) { Name = nameof(FileLogger), Priority = ThreadPriority.Lowest, IsBackground = true };
|
||||
thread.Start();
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
writerAvaliable = false;
|
||||
writerAvailable = false;
|
||||
if (writer is not null) ((IDisposable) writer).Dispose();
|
||||
queuedEvent.Dispose();
|
||||
}
|
||||
|
||||
+13
-6
@@ -1,6 +1,6 @@
|
||||
namespace MeloongCore;
|
||||
public readonly struct OneOf<T0, T1> {
|
||||
private readonly int _index;
|
||||
private readonly int _index = -1; // -1 表示未初始化(这是一个 struct,所以这可以让默认值不为 0)
|
||||
private readonly T0? _value0;
|
||||
private readonly T1? _value1;
|
||||
public static implicit operator OneOf<T0, T1>(T0 value) => new(0, value, default);
|
||||
@@ -17,7 +17,9 @@ public readonly struct OneOf<T0, T1> {
|
||||
/// 对不同类型执行不同的操作,并返回同一个值。
|
||||
/// </summary>
|
||||
public TResult Switch<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1) => _index switch {
|
||||
0 => f0(_value0!), _ => f1(_value1!)
|
||||
0 => f0(_value0!),
|
||||
1 => f1(_value1!),
|
||||
_ => throw new InvalidOperationException()
|
||||
};
|
||||
/// <summary>
|
||||
/// 对不同类型执行不同的操作。
|
||||
@@ -25,6 +27,7 @@ public readonly struct OneOf<T0, T1> {
|
||||
public void Switch(Action<T0> f0, Action<T1> f1) {
|
||||
if (_index == 0) f0(_value0!);
|
||||
else if (_index == 1) f1(_value1!);
|
||||
else throw new InvalidOperationException();
|
||||
}
|
||||
/// <summary>
|
||||
/// 判断当前的类型是否为 T。
|
||||
@@ -36,7 +39,7 @@ public readonly struct OneOf<T0, T1> {
|
||||
};
|
||||
/// <summary>
|
||||
/// 假定当前的类型为 T,并返回该值。
|
||||
/// 若当前值的类型不为 T,则抛出 InvalidOperationException。
|
||||
/// 若当前值的类型不为 T,则抛出 <see cref="InvalidOperationException"/>。
|
||||
/// </summary>
|
||||
public T As<T>() => _index switch {
|
||||
0 when typeof(T) == typeof(T0) => (T)(object)_value0!,
|
||||
@@ -46,7 +49,7 @@ public readonly struct OneOf<T0, T1> {
|
||||
}
|
||||
|
||||
public readonly struct OneOf<T0, T1, T2> {
|
||||
private readonly int _index;
|
||||
private readonly int _index = -1; // -1 表示未初始化(这是一个 struct,所以这可以让默认值不为 0)
|
||||
private readonly T0? _value0;
|
||||
private readonly T1? _value1;
|
||||
private readonly T2? _value2;
|
||||
@@ -67,7 +70,10 @@ public readonly struct OneOf<T0, T1, T2> {
|
||||
/// 对不同类型执行不同的操作,并返回同一个值。
|
||||
/// </summary>
|
||||
public TResult Switch<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2) => _index switch {
|
||||
0 => f0(_value0!), 1 => f1(_value1!), _ => f2(_value2!)
|
||||
0 => f0(_value0!),
|
||||
1 => f1(_value1!),
|
||||
2 => f2(_value2!),
|
||||
_ => throw new InvalidOperationException()
|
||||
};
|
||||
/// <summary>
|
||||
/// 对不同类型执行不同的操作。
|
||||
@@ -76,6 +82,7 @@ public readonly struct OneOf<T0, T1, T2> {
|
||||
if (_index == 0) f0(_value0!);
|
||||
else if (_index == 1) f1(_value1!);
|
||||
else if (_index == 2) f2(_value2!);
|
||||
else throw new InvalidOperationException();
|
||||
}
|
||||
/// <summary>
|
||||
/// 判断当前的类型是否为 T。
|
||||
@@ -88,7 +95,7 @@ public readonly struct OneOf<T0, T1, T2> {
|
||||
};
|
||||
/// <summary>
|
||||
/// 假定当前的类型为 T,并返回该值。
|
||||
/// 若当前值的类型不为 T,则抛出 InvalidOperationException。
|
||||
/// 若当前值的类型不为 T,则抛出 <see cref="InvalidOperationException"/>。
|
||||
/// </summary>
|
||||
public T As<T>() => _index switch {
|
||||
0 when typeof(T) == typeof(T0) => (T) (object) _value0!,
|
||||
|
||||
Reference in new issue
Block a user