项目 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
@@ -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