项目 5 补齐:旧版线程 API(Suspend / Resume / Abort)与 ListBox
- 编译时把 Thread 的 Suspend / Resume / Abort、ThreadState、Sleep、new Thread 改写成平台的 协作式实现:被挂起或终止的线程在 Sleep、后台改控件、调设备类库、弹提示框时停下或结束; ThreadStateException 等行为与 .NET Framework 一致;编辑器不再提示"已过时" - ListBox:列表项、单选、SelectedIndexChanged 先于 Click、删除选中项后取消选中; ComboBox 与 ListBox 共用 ListControl 和列表项集合;设计器工具箱加"列表框" - 评分规则的"包含"对列表框检查所有列表项 - 示例:项目 5 任务 2(烟雾,线程)、任务 3(推送灾情,二维数组、两个窗体、ListBox), 参考答案修正书上直接 Abort 挂起线程、烟雾记成"发现火情"的问题 - 一直不换行的 Console 输出攒满 4096 字符先发出,避免占满内存 - 测试:旧版线程 API、ListBox 事件顺序、两个示例的端到端和评分测试 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8a92354fe4
commit
91b39603a2
36 files changed
+1653
-105
No files matched your search
@@ -79,6 +79,7 @@ public class ADAM4017Helper
|
||||
/// </summary>
|
||||
public ADAM4017ResModel SetData()
|
||||
{
|
||||
LegacyThreads.CheckPoint();
|
||||
var model = new ADAM4017ResModel();
|
||||
if (string.IsNullOrWhiteSpace(_portName)) return model;
|
||||
model.temperatureValue = Read(0);
|
||||
@@ -110,6 +111,7 @@ public class ADAM4150Helper
|
||||
/// <summary>读取人体红外、火焰、烟雾、红外对射;串口未打开时全部为 false</summary>
|
||||
public ADAM4150ResModel SetData()
|
||||
{
|
||||
LegacyThreads.CheckPoint();
|
||||
var model = new ADAM4150ResModel();
|
||||
if (string.IsNullOrWhiteSpace(_portName)) return model;
|
||||
model.bodyInfraredValue = Read(0);
|
||||
|
||||
@@ -7,6 +7,9 @@ namespace Sim.Runner;
|
||||
/// <summary>把学生程序的 Console 输出按行转发给浏览器(标准输出本身留给协议消息使用)</summary>
|
||||
internal sealed class ConsoleForwarder : TextWriter
|
||||
{
|
||||
/// <summary>一直不换行的输出(如教材的 while (true) Console.Write("A"))攒到这么多字符就先发出去</summary>
|
||||
private const int MaxBuffered = 4096;
|
||||
|
||||
private readonly StringBuilder _buffer = new();
|
||||
|
||||
public override Encoding Encoding => Encoding.UTF8;
|
||||
@@ -16,7 +19,7 @@ internal sealed class ConsoleForwarder : TextWriter
|
||||
lock (_buffer)
|
||||
{
|
||||
_buffer.Append(value);
|
||||
if (value == '\n') FlushBuffer();
|
||||
if (value == '\n' || _buffer.Length >= MaxBuffered) FlushBuffer();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +29,7 @@ internal sealed class ConsoleForwarder : TextWriter
|
||||
lock (_buffer)
|
||||
{
|
||||
_buffer.Append(value);
|
||||
if (value.Contains('\n')) FlushBuffer();
|
||||
if (value.Contains('\n') || _buffer.Length >= MaxBuffered) FlushBuffer();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -244,6 +244,7 @@ internal static class LanguageServer
|
||||
foreach (var diagnostic in compilation.GetDiagnostics()
|
||||
.Concat(ApiPolicy.Check(compilation))
|
||||
.Where(d => d.Severity is DiagnosticSeverity.Error or DiagnosticSeverity.Warning && d.Location.IsInSource)
|
||||
.Where(d => !LegacyThreadRewriter.IsSupportedObsoleteWarning(d))
|
||||
.OrderBy(d => d.Severity == DiagnosticSeverity.Error ? 0 : 1))
|
||||
{
|
||||
diagnostics.Add(StudentCompiler.ToJson(diagnostic));
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
|
||||
namespace Sim.Runner;
|
||||
|
||||
/// <summary>
|
||||
/// 编译前改写学生代码里的旧版线程 API,让教材项目 5 的 Suspend / Resume / Abort 能在新版 .NET 上运行:
|
||||
/// <code>
|
||||
/// new Thread(GetData) → new Thread(LegacyThreads.Wrap(new ThreadStart(GetData)))
|
||||
/// thd.Suspend() / Resume() / Abort() → LegacyThreads.Suspend(thd) …
|
||||
/// thd.ThreadState → LegacyThreads.GetThreadState(thd)
|
||||
/// Thread.Sleep(2000) → LegacyThreads.Sleep(2000)
|
||||
/// </code>
|
||||
/// 只改写语义上确实是 System.Threading.Thread 成员的调用;改写不换行,报错和异常堆栈里的行号不变。
|
||||
/// 学生在编辑器里看到的仍是原来的代码。
|
||||
/// </summary>
|
||||
internal static class LegacyThreadRewriter
|
||||
{
|
||||
private const string Target = "global::Sim.Host.LegacyThreads";
|
||||
|
||||
/// <summary>改写整个编译;没有需要改写的地方时原样返回</summary>
|
||||
public static CSharpCompilation Rewrite(CSharpCompilation compilation)
|
||||
{
|
||||
var result = compilation;
|
||||
foreach (var tree in compilation.SyntaxTrees)
|
||||
{
|
||||
// 用到线程的文件一定会出现 Thread 这个词,其他文件不用做语义分析
|
||||
if (!tree.GetText().ToString().Contains("Thread")) continue;
|
||||
var rewriter = new Rewriter(compilation.GetSemanticModel(tree));
|
||||
var root = rewriter.Visit(tree.GetRoot());
|
||||
if (!rewriter.Changed) continue;
|
||||
var text = SourceText.From(root.ToFullString(), Encoding.UTF8);
|
||||
result = result.ReplaceSyntaxTree(tree, CSharpSyntaxTree.ParseText(text, (CSharpParseOptions)tree.Options, tree.FilePath));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>平台支持的过时线程 API 不再提示"已过时"(边写边检查时用)</summary>
|
||||
public static bool IsSupportedObsoleteWarning(Diagnostic diagnostic)
|
||||
{
|
||||
if (diagnostic.Id is not ("CS0618" or "SYSLIB0006")) return false;
|
||||
// 警告标在整个调用上,如 thd.Suspend()
|
||||
var source = diagnostic.Location.SourceTree?.GetText().ToString(diagnostic.Location.SourceSpan) ?? "";
|
||||
return Regex.IsMatch(source, @"\b(Suspend|Resume|Abort)\b");
|
||||
}
|
||||
|
||||
private static bool IsThread(ITypeSymbol? type) =>
|
||||
type is { Name: "Thread", ContainingNamespace: { Name: "Threading", ContainingNamespace: { Name: "System", ContainingNamespace.IsGlobalNamespace: true } } };
|
||||
|
||||
private sealed class Rewriter(SemanticModel model) : CSharpSyntaxRewriter
|
||||
{
|
||||
public bool Changed { get; private set; }
|
||||
|
||||
public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node)
|
||||
{
|
||||
var method = model.GetSymbolInfo(node).Symbol as IMethodSymbol;
|
||||
var visited = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!;
|
||||
if (method == null || !IsThread(method.ContainingType)) return visited;
|
||||
|
||||
switch (method.Name)
|
||||
{
|
||||
case "Suspend" or "Resume" or "Abort" when !method.IsStatic && visited.Expression is MemberAccessExpressionSyntax access:
|
||||
// thd.Abort(x) → LegacyThreads.Abort(thd, x)
|
||||
var arguments = visited.ArgumentList.Arguments.Insert(0, SyntaxFactory.Argument(access.Expression.WithoutTrivia()));
|
||||
Changed = true;
|
||||
return SyntaxFactory.InvocationExpression(Member(method.Name), SyntaxFactory.ArgumentList(arguments))
|
||||
.WithTriviaFrom(visited);
|
||||
case "Sleep" when method.IsStatic:
|
||||
Changed = true;
|
||||
return visited.WithExpression(Member("Sleep").WithTriviaFrom(visited.Expression));
|
||||
default:
|
||||
return visited;
|
||||
}
|
||||
}
|
||||
|
||||
public override SyntaxNode? VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
|
||||
{
|
||||
var symbol = model.GetSymbolInfo(node).Symbol;
|
||||
var visited = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!;
|
||||
if (symbol is not IPropertySymbol { Name: "ThreadState", IsStatic: false } property || !IsThread(property.ContainingType)) return visited;
|
||||
Changed = true;
|
||||
return SyntaxFactory.InvocationExpression(
|
||||
Member("GetThreadState"),
|
||||
SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Argument(visited.Expression.WithoutTrivia()))))
|
||||
.WithTriviaFrom(visited);
|
||||
}
|
||||
|
||||
public override SyntaxNode? VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) =>
|
||||
WrapThreadStart(node, base.VisitObjectCreationExpression(node));
|
||||
|
||||
public override SyntaxNode? VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) =>
|
||||
WrapThreadStart(node, base.VisitImplicitObjectCreationExpression(node));
|
||||
|
||||
/// <summary>new Thread(start) 的第一个参数包一层 LegacyThreads.Wrap,线程被 Abort 时安静地结束</summary>
|
||||
private SyntaxNode? WrapThreadStart(BaseObjectCreationExpressionSyntax original, SyntaxNode? visitedNode)
|
||||
{
|
||||
if (visitedNode is not BaseObjectCreationExpressionSyntax visited
|
||||
|| model.GetSymbolInfo(original).Symbol is not IMethodSymbol { MethodKind: MethodKind.Constructor } constructor
|
||||
|| !IsThread(constructor.ContainingType)
|
||||
|| constructor.Parameters.Length == 0
|
||||
|| visited.ArgumentList is not { Arguments.Count: > 0 } argumentList)
|
||||
{
|
||||
return visitedNode;
|
||||
}
|
||||
var first = argumentList.Arguments[0];
|
||||
if (first.Expression.IsKind(SyntaxKind.NullLiteralExpression)) return visited;
|
||||
var delegateType = constructor.Parameters[0].Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
|
||||
// new ThreadStart(方法名或 lambda):明确委托类型,Wrap 的重载就不会有歧义
|
||||
var wrapped = SyntaxFactory.ParseExpression($"{Target}.Wrap(new {delegateType}({first.Expression.WithoutTrivia().ToFullString()}))");
|
||||
Changed = true;
|
||||
return visited.WithArgumentList(argumentList.WithArguments(
|
||||
argumentList.Arguments.Replace(first, first.WithExpression(wrapped.WithTriviaFrom(first.Expression)))));
|
||||
}
|
||||
|
||||
private static ExpressionSyntax Member(string name) => SyntaxFactory.ParseExpression($"{Target}.{name}");
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,8 @@ internal static class StudentCompiler
|
||||
|
||||
using var peStream = new MemoryStream();
|
||||
using var pdbStream = new MemoryStream();
|
||||
var emit = compilation.Emit(peStream, pdbStream,
|
||||
// 编译改写后的代码(旧版线程 API 换成平台实现),API 检查仍针对学生写的原始代码
|
||||
var emit = LegacyThreadRewriter.Rewrite(compilation).Emit(peStream, pdbStream,
|
||||
options: new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb));
|
||||
var denied = ApiPolicy.Check(compilation).ToList();
|
||||
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Text.Json.Nodes;
|
||||
using Sim.Host;
|
||||
|
||||
namespace System.Windows.Forms;
|
||||
|
||||
public class ComboBox : Control
|
||||
public class ComboBox : ListControl
|
||||
{
|
||||
private int _selectedIndex = -1;
|
||||
private ComboBoxStyle _dropDownStyle = ComboBoxStyle.DropDown;
|
||||
|
||||
public ComboBox() => Items = new ObjectCollection(this);
|
||||
@@ -31,15 +27,15 @@ public class ComboBox : Control
|
||||
set => SetProp(ref _dropDownStyle, value, nameof(DropDownStyle));
|
||||
}
|
||||
|
||||
public int SelectedIndex
|
||||
public override int SelectedIndex
|
||||
{
|
||||
get => _selectedIndex;
|
||||
get => SelectedIndexValue;
|
||||
set
|
||||
{
|
||||
if (value < -1 || value >= Items.Count)
|
||||
throw new ArgumentOutOfRangeException(nameof(value), $"“{value}”的值对于“SelectedIndex”无效。");
|
||||
if (value == _selectedIndex) return;
|
||||
SetProp(ref _selectedIndex, value, nameof(SelectedIndex));
|
||||
if (value == SelectedIndexValue) return;
|
||||
SetProp(ref SelectedIndexValue, value, nameof(SelectedIndex));
|
||||
// 选中项变化时 Text 随之变化(先 TextChanged,再 SelectedIndexChanged,与 WinForms 一致)
|
||||
Text = value >= 0 ? Items[value]?.ToString() ?? "" : "";
|
||||
OnSelectedIndexChanged(EventArgs.Empty);
|
||||
@@ -49,19 +45,17 @@ public class ComboBox : Control
|
||||
|
||||
public object? SelectedItem
|
||||
{
|
||||
get => _selectedIndex >= 0 ? Items[_selectedIndex] : null;
|
||||
get => SelectedIndexValue >= 0 ? Items[SelectedIndexValue] : null;
|
||||
set => SelectedIndex = value == null ? -1 : Items.IndexOf(value);
|
||||
}
|
||||
|
||||
public string SelectedText { get; set; } = "";
|
||||
|
||||
public event EventHandler? SelectedIndexChanged;
|
||||
public event EventHandler? SelectedValueChanged;
|
||||
public event EventHandler? DropDown;
|
||||
public event EventHandler? DropDownClosed;
|
||||
|
||||
protected virtual void OnSelectedIndexChanged(EventArgs e) => SelectedIndexChanged?.Invoke(this, e);
|
||||
protected virtual void OnSelectedValueChanged(EventArgs e) => SelectedValueChanged?.Invoke(this, e);
|
||||
protected virtual void OnDropDown(EventArgs e) => DropDown?.Invoke(this, e);
|
||||
protected virtual void OnDropDownClosed(EventArgs e) => DropDownClosed?.Invoke(this, e);
|
||||
|
||||
@@ -84,7 +78,7 @@ public class ComboBox : Control
|
||||
case "text" when _dropDownStyle != ComboBoxStyle.DropDownList:
|
||||
SetTextFromUser(action.Value ?? "");
|
||||
var match = Items.IndexOf(Text);
|
||||
if (match != _selectedIndex) _selectedIndex = match;
|
||||
if (match != SelectedIndexValue) SelectedIndexValue = match;
|
||||
break;
|
||||
default:
|
||||
base.OnUserAction(action);
|
||||
@@ -92,85 +86,28 @@ public class ComboBox : Control
|
||||
}
|
||||
}
|
||||
|
||||
internal void ItemsChanged()
|
||||
internal override void ItemsChanged()
|
||||
{
|
||||
if (_selectedIndex >= Items.Count) _selectedIndex = -1;
|
||||
NotifyChanged(nameof(Items), Items.Select(i => i?.ToString() ?? "").ToArray());
|
||||
NotifyChanged(nameof(Items), ItemTexts(Items));
|
||||
NotifyChanged(nameof(SelectedIndex), SelectedIndexValue);
|
||||
}
|
||||
|
||||
internal override void ItemsCleared()
|
||||
{
|
||||
SelectedIndex = -1;
|
||||
ItemsChanged();
|
||||
}
|
||||
|
||||
protected override void WriteProps(JsonObject props)
|
||||
{
|
||||
base.WriteProps(props);
|
||||
props["Items"] = PropValue.From(Items.Select(i => i?.ToString() ?? "").ToArray());
|
||||
props["SelectedIndex"] = _selectedIndex;
|
||||
props["Items"] = PropValue.From(ItemTexts(Items));
|
||||
props["SelectedIndex"] = SelectedIndexValue;
|
||||
props["DropDownStyle"] = _dropDownStyle.ToString();
|
||||
}
|
||||
|
||||
public class ObjectCollection : IList, IEnumerable<object?>
|
||||
public class ObjectCollection : ListItemCollection
|
||||
{
|
||||
private readonly List<object?> _items = new();
|
||||
private readonly ComboBox _owner;
|
||||
|
||||
public ObjectCollection(ComboBox owner) => _owner = owner;
|
||||
|
||||
public int Count => _items.Count;
|
||||
public bool IsReadOnly => false;
|
||||
bool IList.IsFixedSize => false;
|
||||
bool ICollection.IsSynchronized => false;
|
||||
object ICollection.SyncRoot => this;
|
||||
|
||||
public object? this[int index]
|
||||
{
|
||||
get => _items[index];
|
||||
set
|
||||
{
|
||||
_items[index] = value;
|
||||
_owner.ItemsChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public int Add(object? item)
|
||||
{
|
||||
if (item == null) throw new ArgumentNullException(nameof(item), "值不能为 null。");
|
||||
_items.Add(item);
|
||||
_owner.ItemsChanged();
|
||||
return _items.Count - 1;
|
||||
}
|
||||
|
||||
public void AddRange(object[] items)
|
||||
{
|
||||
_items.AddRange(items);
|
||||
_owner.ItemsChanged();
|
||||
}
|
||||
|
||||
public void Insert(int index, object? item)
|
||||
{
|
||||
_items.Insert(index, item);
|
||||
_owner.ItemsChanged();
|
||||
}
|
||||
|
||||
public void Remove(object? item)
|
||||
{
|
||||
if (_items.Remove(item)) _owner.ItemsChanged();
|
||||
}
|
||||
|
||||
public void RemoveAt(int index)
|
||||
{
|
||||
_items.RemoveAt(index);
|
||||
_owner.ItemsChanged();
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_items.Clear();
|
||||
_owner.SelectedIndex = -1;
|
||||
_owner.ItemsChanged();
|
||||
}
|
||||
|
||||
public bool Contains(object? item) => _items.Contains(item);
|
||||
public int IndexOf(object? item) => _items.IndexOf(item);
|
||||
public void CopyTo(Array array, int index) => ((ICollection)_items).CopyTo(array, index);
|
||||
public IEnumerator<object?> GetEnumerator() => _items.GetEnumerator();
|
||||
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
|
||||
public ObjectCollection(ComboBox owner) : base(owner) { }
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,7 @@ public class Control : Component, IWin32Window
|
||||
get => _text;
|
||||
set
|
||||
{
|
||||
LegacyThreads.CheckPoint();
|
||||
value ??= "";
|
||||
if (_text == value) return;
|
||||
EnsureThreadAccess();
|
||||
@@ -279,6 +280,9 @@ public class Control : Component, IWin32Window
|
||||
OnClick(args);
|
||||
OnMouseClick(args);
|
||||
break;
|
||||
case "doubleClick":
|
||||
OnDoubleClick(EventArgs.Empty);
|
||||
break;
|
||||
case "mouseDown":
|
||||
OnMouseDown(new MouseEventArgs(ToMouseButtons(action.Button), 1, action.X, action.Y, 0));
|
||||
break;
|
||||
@@ -354,6 +358,8 @@ public class Control : Component, IWin32Window
|
||||
/// <summary>修改字段并在需要时通知浏览器;返回值表示是否真的改变</summary>
|
||||
protected bool SetProp<T>(ref T field, T value, string prop)
|
||||
{
|
||||
// 后台线程改界面时响应 Suspend / Abort(教材的线程方法每次循环都会改控件)
|
||||
LegacyThreads.CheckPoint();
|
||||
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
|
||||
EnsureThreadAccess();
|
||||
field = value;
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
using System.Drawing;
|
||||
using System.Text.Json.Nodes;
|
||||
using Sim.Host;
|
||||
|
||||
namespace System.Windows.Forms;
|
||||
|
||||
public enum SelectionMode { None, One, MultiSimple, MultiExtended }
|
||||
|
||||
/// <summary>列表框(教材项目 5 任务 3 显示历史灾情记录)。只支持单选。</summary>
|
||||
public class ListBox : ListControl
|
||||
{
|
||||
private int _itemHeight = 12;
|
||||
private BorderStyle _borderStyle = BorderStyle.Fixed3D;
|
||||
|
||||
public ListBox() => Items = new ObjectCollection(this);
|
||||
|
||||
protected override Size DefaultSize => new(120, 96);
|
||||
|
||||
public ObjectCollection Items { get; }
|
||||
|
||||
public bool FormattingEnabled { get; set; }
|
||||
public bool IntegralHeight { get; set; } = true;
|
||||
public bool HorizontalScrollbar { get; set; }
|
||||
public bool ScrollAlwaysVisible { get; set; }
|
||||
public bool MultiColumn { get; set; }
|
||||
public bool Sorted { get; set; }
|
||||
public SelectionMode SelectionMode { get; set; } = SelectionMode.One;
|
||||
public int TopIndex { get; set; }
|
||||
|
||||
public int ItemHeight
|
||||
{
|
||||
get => _itemHeight;
|
||||
set => SetProp(ref _itemHeight, value, nameof(ItemHeight));
|
||||
}
|
||||
|
||||
public BorderStyle BorderStyle
|
||||
{
|
||||
get => _borderStyle;
|
||||
set => SetProp(ref _borderStyle, value, nameof(BorderStyle));
|
||||
}
|
||||
|
||||
public override int SelectedIndex
|
||||
{
|
||||
get => SelectedIndexValue;
|
||||
set
|
||||
{
|
||||
if (value < -1 || value >= Items.Count)
|
||||
throw new ArgumentOutOfRangeException(nameof(value), $"“{value}”的值对于“SelectedIndex”无效。");
|
||||
if (!SetProp(ref SelectedIndexValue, value, nameof(SelectedIndex))) return;
|
||||
OnSelectedIndexChanged(EventArgs.Empty);
|
||||
OnSelectedValueChanged(EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
public object? SelectedItem
|
||||
{
|
||||
get => SelectedIndexValue >= 0 ? Items[SelectedIndexValue] : null;
|
||||
set => SelectedIndex = value == null ? -1 : Items.IndexOf(value);
|
||||
}
|
||||
|
||||
/// <summary>和 WinForms 一样,列表框的 Text 是选中项的文字;赋值时选中文字相同的项</summary>
|
||||
public override string Text
|
||||
{
|
||||
get => GetItemText(SelectedItem);
|
||||
set
|
||||
{
|
||||
var index = FindStringExact(value ?? "");
|
||||
if (index >= 0) SelectedIndex = index;
|
||||
}
|
||||
}
|
||||
|
||||
public event EventHandler? SelectedIndexChanged;
|
||||
|
||||
protected virtual void OnSelectedIndexChanged(EventArgs e) => SelectedIndexChanged?.Invoke(this, e);
|
||||
|
||||
public void ClearSelected() => SelectedIndex = -1;
|
||||
|
||||
public void SetSelected(int index, bool value)
|
||||
{
|
||||
if (value) SelectedIndex = index;
|
||||
else if (index == SelectedIndexValue) SelectedIndex = -1;
|
||||
}
|
||||
|
||||
public bool GetSelected(int index) => index == SelectedIndexValue;
|
||||
|
||||
/// <summary>第一个以 s 开头的项(不区分大小写),没有时返回 -1</summary>
|
||||
public int FindString(string s)
|
||||
{
|
||||
for (var i = 0; i < Items.Count; i++)
|
||||
if (GetItemText(Items[i]).StartsWith(s, StringComparison.OrdinalIgnoreCase)) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
public int FindStringExact(string s)
|
||||
{
|
||||
for (var i = 0; i < Items.Count; i++)
|
||||
if (string.Equals(GetItemText(Items[i]), s, StringComparison.OrdinalIgnoreCase)) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
public void BeginUpdate() { }
|
||||
public void EndUpdate() { }
|
||||
|
||||
protected override void OnUserAction(UserAction action)
|
||||
{
|
||||
switch (action.Action)
|
||||
{
|
||||
case "select":
|
||||
// 和 WinForms 一样,按下鼠标时先改变选中项,松开后才触发 Click
|
||||
if (action.Index >= 0 && action.Index < Items.Count) SelectedIndex = action.Index;
|
||||
base.OnUserAction(new UserAction { Action = "click", X = action.X, Y = action.Y });
|
||||
break;
|
||||
default:
|
||||
base.OnUserAction(action);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
internal override void ItemsChanged()
|
||||
{
|
||||
NotifyChanged(nameof(Items), ItemTexts(Items));
|
||||
NotifyChanged(nameof(SelectedIndex), SelectedIndexValue);
|
||||
}
|
||||
|
||||
internal override void ItemsCleared()
|
||||
{
|
||||
SelectedIndex = -1;
|
||||
ItemsChanged();
|
||||
}
|
||||
|
||||
protected override void WriteProps(JsonObject props)
|
||||
{
|
||||
base.WriteProps(props);
|
||||
props["Items"] = PropValue.From(ItemTexts(Items));
|
||||
props["SelectedIndex"] = SelectedIndexValue;
|
||||
props["ItemHeight"] = _itemHeight;
|
||||
props["BorderStyle"] = _borderStyle.ToString();
|
||||
}
|
||||
|
||||
public class ObjectCollection : ListItemCollection
|
||||
{
|
||||
public ObjectCollection(ListBox owner) : base(owner) { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace System.Windows.Forms;
|
||||
|
||||
/// <summary>ComboBox 和 ListBox 的共同基类:列表项、选中项</summary>
|
||||
public abstract class ListControl : Control
|
||||
{
|
||||
/// <summary>选中项的序号。列表项增删时直接调整(和 WinForms 一样不触发 SelectedIndexChanged)</summary>
|
||||
private protected int SelectedIndexValue = -1;
|
||||
|
||||
public abstract int SelectedIndex { get; set; }
|
||||
|
||||
public string DisplayMember { get; set; } = "";
|
||||
public string ValueMember { get; set; } = "";
|
||||
|
||||
public event EventHandler? SelectedValueChanged;
|
||||
|
||||
protected virtual void OnSelectedValueChanged(EventArgs e) => SelectedValueChanged?.Invoke(this, e);
|
||||
|
||||
public string GetItemText(object? item) => item?.ToString() ?? "";
|
||||
|
||||
/// <summary>列表项变化后调用:把新的列表和选中项发给浏览器</summary>
|
||||
internal abstract void ItemsChanged();
|
||||
|
||||
/// <summary>Items.Clear() 时调用:先取消选中,再刷新列表</summary>
|
||||
internal abstract void ItemsCleared();
|
||||
|
||||
internal void ItemInserted(int index)
|
||||
{
|
||||
if (SelectedIndexValue >= index) SelectedIndexValue++;
|
||||
ItemsChanged();
|
||||
}
|
||||
|
||||
/// <summary>删掉的正是选中项时取消选中,删掉前面的项时选中项序号前移</summary>
|
||||
internal void ItemRemoved(int index)
|
||||
{
|
||||
if (SelectedIndexValue == index) SelectedIndexValue = -1;
|
||||
else if (SelectedIndexValue > index) SelectedIndexValue--;
|
||||
ItemsChanged();
|
||||
}
|
||||
|
||||
protected string[] ItemTexts(IEnumerable<object?> items) => items.Select(GetItemText).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>ComboBox.ObjectCollection 和 ListBox.ObjectCollection 共用的实现</summary>
|
||||
public abstract class ListItemCollection : IList, IEnumerable<object?>
|
||||
{
|
||||
private readonly List<object?> _items = new();
|
||||
private readonly ListControl _owner;
|
||||
|
||||
private protected ListItemCollection(ListControl owner) => _owner = owner;
|
||||
|
||||
public int Count => _items.Count;
|
||||
public bool IsReadOnly => false;
|
||||
bool IList.IsFixedSize => false;
|
||||
bool ICollection.IsSynchronized => false;
|
||||
object ICollection.SyncRoot => this;
|
||||
|
||||
public object? this[int index]
|
||||
{
|
||||
get => _items[index];
|
||||
set
|
||||
{
|
||||
_items[index] = value;
|
||||
_owner.ItemsChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public int Add(object? item)
|
||||
{
|
||||
if (item == null) throw new ArgumentNullException(nameof(item), "值不能为 null。");
|
||||
_items.Add(item);
|
||||
_owner.ItemsChanged();
|
||||
return _items.Count - 1;
|
||||
}
|
||||
|
||||
public void AddRange(object[] items)
|
||||
{
|
||||
_items.AddRange(items);
|
||||
_owner.ItemsChanged();
|
||||
}
|
||||
|
||||
public void Insert(int index, object? item)
|
||||
{
|
||||
_items.Insert(index, item);
|
||||
_owner.ItemInserted(index);
|
||||
}
|
||||
|
||||
public void Remove(object? item)
|
||||
{
|
||||
var index = _items.IndexOf(item);
|
||||
if (index >= 0) RemoveAt(index);
|
||||
}
|
||||
|
||||
public void RemoveAt(int index)
|
||||
{
|
||||
_items.RemoveAt(index);
|
||||
_owner.ItemRemoved(index);
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_items.Clear();
|
||||
_owner.ItemsCleared();
|
||||
}
|
||||
|
||||
public bool Contains(object? item) => _items.Contains(item);
|
||||
public int IndexOf(object? item) => _items.IndexOf(item);
|
||||
public void CopyTo(Array array, int index) => ((ICollection)_items).CopyTo(array, index);
|
||||
public IEnumerator<object?> GetEnumerator() => _items.GetEnumerator();
|
||||
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace Sim.Host;
|
||||
|
||||
/// <summary>
|
||||
/// 教材项目 5 用到的旧版线程 API:Thread.Suspend / Resume / Abort 在新版 .NET 上会抛出 PlatformNotSupportedException。
|
||||
/// 编译时把学生代码里对它们(以及 new Thread、Thread.Sleep、ThreadState)的调用改写成这里的方法(见 Sim.Runner/LegacyThreadRewriter.cs)。
|
||||
/// <para>
|
||||
/// 新版 .NET 不能从外部强行停住或中止一个线程,所以这里是"协作式"的:被挂起或中止的线程在下一个检查点停下或结束。
|
||||
/// 检查点是 Thread.Sleep、从后台线程修改控件属性、调用设备类库、弹出提示框,
|
||||
/// 教材里的线程方法每次循环都会经过它们,看到的效果和 .NET Framework 一致。
|
||||
/// </para>
|
||||
/// </summary>
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public static class LegacyThreads
|
||||
{
|
||||
private sealed class State
|
||||
{
|
||||
public volatile bool Suspended;
|
||||
public volatile bool AbortRequested;
|
||||
}
|
||||
|
||||
// 线程少、操作不频繁,用一把锁保护所有线程的状态;挂起和休眠都在这把锁上等待
|
||||
private static readonly object Gate = new();
|
||||
private static readonly ConditionalWeakTable<Thread, State> States = new();
|
||||
|
||||
/// <summary>当前线程是学生用 new Thread 创建的线程时,指向它的状态</summary>
|
||||
[ThreadStatic] private static State? _current;
|
||||
|
||||
private static State StateOf(Thread thread) => States.GetValue(thread, static _ => new State());
|
||||
|
||||
// ---------- 改写后的调用 ----------
|
||||
|
||||
/// <summary>new Thread(GetData) → new Thread(Wrap(new ThreadStart(GetData))):线程被中止时安静地结束</summary>
|
||||
public static ThreadStart Wrap(ThreadStart start) => () => RunThread(() => start());
|
||||
|
||||
public static ParameterizedThreadStart Wrap(ParameterizedThreadStart start) => obj => RunThread(() => start(obj));
|
||||
|
||||
private static void RunThread(Action body)
|
||||
{
|
||||
var state = StateOf(Thread.CurrentThread);
|
||||
_current = state;
|
||||
try
|
||||
{
|
||||
// 启动前就被 Abort 的线程(.NET Framework 里启动后立即结束)
|
||||
CheckPoint(state);
|
||||
body();
|
||||
}
|
||||
catch (ThreadAbortedException)
|
||||
{
|
||||
// 和 .NET Framework 一样,被中止的线程结束时不算未处理的异常
|
||||
}
|
||||
}
|
||||
|
||||
public static void Suspend(Thread thread)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
if ((thread.ThreadState & (ThreadState.Unstarted | ThreadState.Stopped)) != 0)
|
||||
throw new ThreadStateException("线程没有在运行,无法挂起。");
|
||||
StateOf(thread).Suspended = true;
|
||||
}
|
||||
// 线程挂起自己:立即停下,直到别的线程调用 Resume
|
||||
if (thread == Thread.CurrentThread) CheckPoint(StateOf(thread));
|
||||
}
|
||||
|
||||
public static void Resume(Thread thread)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
var state = StateOf(thread);
|
||||
if (!state.Suspended) throw new ThreadStateException("线程没有被挂起,无法继续(Resume 只能用在调用过 Suspend 的线程上)。");
|
||||
state.Suspended = false;
|
||||
Monitor.PulseAll(Gate);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Abort(Thread thread) => Abort(thread, null);
|
||||
|
||||
public static void Abort(Thread thread, object? stateInfo)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
if ((thread.ThreadState & ThreadState.Stopped) != 0) return;
|
||||
var state = StateOf(thread);
|
||||
state.AbortRequested = true;
|
||||
// 正在 Thread.Sleep 的线程立即醒来结束
|
||||
Monitor.PulseAll(Gate);
|
||||
// .NET Framework 不能直接中止挂起的线程:抛出异常,等它被 Resume 后才结束
|
||||
if (state.Suspended) throw new ThreadStateException("线程已挂起,不能直接终止。先调用 Resume() 让线程继续,再调用 Abort()。");
|
||||
}
|
||||
if (thread == Thread.CurrentThread) throw new ThreadAbortedException();
|
||||
}
|
||||
|
||||
/// <summary>thd.ThreadState:在真实状态上加上挂起、请求中止</summary>
|
||||
public static ThreadState GetThreadState(Thread thread)
|
||||
{
|
||||
var actual = thread.ThreadState;
|
||||
if (!States.TryGetValue(thread, out var state) || (actual & ThreadState.Stopped) != 0) return actual;
|
||||
var result = actual & (ThreadState.Background | ThreadState.Unstarted);
|
||||
if (state.Suspended) result |= ThreadState.Suspended;
|
||||
else if ((actual & ThreadState.Unstarted) == 0) result |= actual & ThreadState.WaitSleepJoin;
|
||||
if (state.AbortRequested) result |= ThreadState.AbortRequested;
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void Sleep(int millisecondsTimeout)
|
||||
{
|
||||
var state = _current;
|
||||
if (state == null)
|
||||
{
|
||||
Thread.Sleep(millisecondsTimeout);
|
||||
return;
|
||||
}
|
||||
if (millisecondsTimeout < Timeout.Infinite) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), "休眠时间不能是负数(-1 表示一直休眠)。");
|
||||
CheckPoint(state);
|
||||
var deadline = Environment.TickCount64 + millisecondsTimeout;
|
||||
lock (Gate)
|
||||
{
|
||||
// 休眠中被 Abort 时提前醒来;被 Suspend 的线程睡完后在检查点停下
|
||||
while (!state.AbortRequested)
|
||||
{
|
||||
if (millisecondsTimeout == Timeout.Infinite)
|
||||
{
|
||||
Monitor.Wait(Gate);
|
||||
continue;
|
||||
}
|
||||
var remaining = deadline - Environment.TickCount64;
|
||||
if (remaining <= 0) break;
|
||||
Monitor.Wait(Gate, (int)remaining);
|
||||
}
|
||||
}
|
||||
CheckPoint(state);
|
||||
}
|
||||
|
||||
public static void Sleep(TimeSpan timeout) => Sleep((int)timeout.TotalMilliseconds);
|
||||
|
||||
// ---------- 检查点 ----------
|
||||
|
||||
/// <summary>平台内部使用:学生创建的线程在这里响应 Suspend 和 Abort(其他线程直接返回)</summary>
|
||||
public static void CheckPoint()
|
||||
{
|
||||
var state = _current;
|
||||
if (state != null) CheckPoint(state);
|
||||
}
|
||||
|
||||
private static void CheckPoint(State state)
|
||||
{
|
||||
if (!state.Suspended && !state.AbortRequested) return;
|
||||
lock (Gate)
|
||||
{
|
||||
while (state.Suspended) Monitor.Wait(Gate);
|
||||
if (state.AbortRequested) throw new ThreadAbortedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>线程被 Abort 时在线程里抛出(对应 .NET Framework 的 ThreadAbortException)</summary>
|
||||
public sealed class ThreadAbortedException : Exception
|
||||
{
|
||||
public ThreadAbortedException() : base("正在中止线程。") { }
|
||||
}
|
||||
@@ -77,13 +77,17 @@ public static class SimHost
|
||||
|
||||
public static void SendConsole(string text) => Send(new JsonObject { ["type"] = "console", ["text"] = text });
|
||||
|
||||
public static void SendDevice(string device, string action, object? data) => Send(new JsonObject
|
||||
public static void SendDevice(string device, string action, object? data)
|
||||
{
|
||||
["type"] = "device",
|
||||
["device"] = device,
|
||||
["action"] = action,
|
||||
["data"] = PropValue.From(data),
|
||||
});
|
||||
LegacyThreads.CheckPoint();
|
||||
Send(new JsonObject
|
||||
{
|
||||
["type"] = "device",
|
||||
["device"] = device,
|
||||
["action"] = action,
|
||||
["data"] = PropValue.From(data),
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 异常 ----------
|
||||
|
||||
@@ -121,6 +125,7 @@ public static class SimHost
|
||||
/// </summary>
|
||||
public static JsonNode? Request(JsonObject message)
|
||||
{
|
||||
LegacyThreads.CheckPoint();
|
||||
var id = Interlocked.Increment(ref _nextRequestId);
|
||||
var pending = new PendingRequest();
|
||||
Requests[id] = pending;
|
||||
|
||||
Reference in new issue
Block a user