├── IdleBus
├── yxq.snk
├── HashedWheelTimer_Impl.zip
├── IdleBus`1.NoticeEventArgs.cs
├── IdleBus`1.NoticeType.cs
├── IdleBus.cs
├── IdleBus`1.Test.cs
├── IdleBus.csproj
├── IdleBus`1.ItemInfo.cs
├── IdleBus`1.ThreadScan.cs
├── IdleBus.xml
└── IdleBus`1.cs
├── IdleScheduler
├── readme.md
└── IdleScheduler.csproj
├── Examples
├── Examples_IdleBus_WinformNet40
│ ├── Properties
│ │ ├── Settings.settings
│ │ ├── AssemblyInfo.cs
│ │ ├── Settings.Designer.cs
│ │ ├── Resources.Designer.cs
│ │ └── Resources.resx
│ ├── Program.cs
│ ├── Form1.cs
│ ├── Examples_IdleBus_WinformNet40.csproj
│ ├── Form1.resx
│ └── Form1.Designer.cs
├── Examples_IdleBus_Quickstart
│ ├── Examples_IdleBus_Quickstart.csproj
│ └── Program.cs
└── Examples_IdleBus_Core31
│ ├── Examples_IdleBus_Core31.csproj
│ └── Program.cs
├── .gitattributes
├── IdleBus.sln
├── readme.md
└── .gitignore
/IdleBus/yxq.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/2881099/IdleBus/HEAD/IdleBus/yxq.snk
--------------------------------------------------------------------------------
/IdleBus/HashedWheelTimer_Impl.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/2881099/IdleBus/HEAD/IdleBus/HashedWheelTimer_Impl.zip
--------------------------------------------------------------------------------
/IdleScheduler/readme.md:
--------------------------------------------------------------------------------
1 | ## IdleScheduler 已正式改名为 FreeScheduler
2 |
3 | ## 源码已迁移至:[https://github.com/2881099/FreeScheduler](https://github.com/2881099/FreeScheduler)
4 |
5 | ## Nuget 包名已改名为:FreeScheduler
--------------------------------------------------------------------------------
/Examples/Examples_IdleBus_WinformNet40/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Examples/Examples_IdleBus_Quickstart/Examples_IdleBus_Quickstart.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Examples/Examples_IdleBus_Core31/Examples_IdleBus_Core31.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Examples/Examples_IdleBus_WinformNet40/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Windows.Forms;
5 |
6 | namespace Examples_IdleBus_WinformNet40
7 | {
8 | static class Program
9 | {
10 | ///
11 | /// 应用程序的主入口点。
12 | ///
13 | [STAThread]
14 | static void Main()
15 | {
16 | Application.EnableVisualStyles();
17 | Application.SetCompatibleTextRenderingDefault(false);
18 | Application.Run(new Form1());
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/IdleBus/IdleBus`1.NoticeEventArgs.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Concurrent;
3 | using System.Collections.Generic;
4 | using System.Diagnostics;
5 | using System.Text;
6 | using System.Threading;
7 |
8 | partial class IdleBus
9 | {
10 |
11 | public class NoticeEventArgs : EventArgs
12 | {
13 |
14 | public NoticeType NoticeType { get; }
15 | public TKey Key { get; }
16 | public Exception Exception { get; }
17 | public string Log { get; }
18 |
19 | public NoticeEventArgs(NoticeType noticeType, TKey key, Exception exception, string log)
20 | {
21 | this.NoticeType = noticeType;
22 | this.Key = key;
23 | this.Exception = exception;
24 | this.Log = log;
25 | }
26 |
27 | }
28 |
29 | }
--------------------------------------------------------------------------------
/IdleBus/IdleBus`1.NoticeType.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Concurrent;
3 | using System.Collections.Generic;
4 | using System.Diagnostics;
5 | using System.Text;
6 | using System.Threading;
7 |
8 | partial class IdleBus
9 | {
10 |
11 | public enum NoticeType
12 | {
13 |
14 | ///
15 | /// 执行 Register 方法的时候
16 | ///
17 | Register,
18 |
19 | ///
20 | /// 执行 Remove 方法的时候,注意:实际会延时释放【实例】
21 | ///
22 | Remove,
23 |
24 | ///
25 | /// 自动创建【实例】的时候
26 | ///
27 | AutoCreate,
28 |
29 | ///
30 | /// 自动释放不活跃【实例】的时候
31 | ///
32 | AutoRelease,
33 |
34 | ///
35 | /// 获取【实例】的时候
36 | ///
37 | Get
38 |
39 | }
40 |
41 | }
--------------------------------------------------------------------------------
/IdleBus/IdleBus.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Concurrent;
3 | using System.Collections.Generic;
4 | using System.Diagnostics;
5 | using System.Text;
6 | using System.Threading;
7 |
8 | ///
9 | /// 空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题
10 | ///
11 | public class IdleBus : IdleBus
12 | {
13 | ///
14 | /// 按空闲时间1分钟,创建空闲容器
15 | ///
16 | public IdleBus() : base() { }
17 | ///
18 | /// 指定空闲时间、创建空闲容器
19 | ///
20 | /// 空闲时间
21 | public IdleBus(TimeSpan idle) : base(idle) { }
22 | }
23 |
24 | ///
25 | /// 空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题
26 | ///
27 | public class IdleBus : IdleBus where TValue : class, IDisposable
28 | {
29 | ///
30 | /// 按空闲时间1分钟,创建空闲容器
31 | ///
32 | public IdleBus() : base() { }
33 | ///
34 | /// 指定空闲时间、创建空闲容器
35 | ///
36 | /// 空闲时间
37 | public IdleBus(TimeSpan idle) : base(idle) { }
38 | }
39 |
--------------------------------------------------------------------------------
/Examples/Examples_IdleBus_WinformNet40/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("Test")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("Test")]
13 | [assembly: AssemblyCopyright("Copyright © 2019")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 会使此程序集中的类型
18 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("0fc8305a-114e-4792-9226-726fe3651cb0")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
33 | //通过使用 "*",如下所示:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/IdleBus/IdleBus`1.Test.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Concurrent;
3 | using System.Collections.Generic;
4 | using System.Diagnostics;
5 | using System.Text;
6 | using System.Threading;
7 |
8 | partial class IdleBus
9 | {
10 |
11 | public static void Test()
12 | {
13 | //超过1分钟没有使用,连续检测2次都这样,就销毁【实例】
14 | var ib = new IdleBus(TimeSpan.FromMinutes(1));
15 | ib.Notice += (_, e) =>
16 | {
17 | var log = $"[{DateTime.Now.ToString("HH:mm:ss")}] 线程{Thread.CurrentThread.ManagedThreadId}:{e.Log}";
18 | //Trace.WriteLine(log);
19 | Console.WriteLine(log);
20 | };
21 |
22 | ib.Register("key1", () => new ManualResetEvent(false));
23 | ib.Register("key2", () => new AutoResetEvent(false));
24 |
25 | var item = ib.Get("key2") as AutoResetEvent;
26 | //获得 key2 对象,创建
27 |
28 | item = ib.Get("key2") as AutoResetEvent;
29 | //获得 key2 对象,已创建
30 |
31 | int num1 = ib.UsageQuantity;
32 | //【实例】有效数量(即已经创建了的),后台定时清理不活跃的【实例】,此值就会减少
33 |
34 | ib.Dispose();
35 | }
36 |
37 | }
--------------------------------------------------------------------------------
/Examples/Examples_IdleBus_WinformNet40/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本:4.0.30319.42000
5 | //
6 | // 对此文件的更改可能会导致不正确的行为,并且如果
7 | // 重新生成代码,这些更改将会丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace Examples_IdleBus_WinformNet40.Properties {
12 |
13 |
14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.4.0.0")]
16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
17 |
18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
19 |
20 | public static Settings Default {
21 | get {
22 | return defaultInstance;
23 | }
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/IdleScheduler/IdleScheduler.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0;net40
5 | 1.5.2.9
6 | true
7 | YeXiangQin
8 | IdleScheduler 轻量定时任务调度,支持临时的延时任务和重复循环任务,可按秒,每天固定时间,每周固定时间,每月固定时间执行。
9 | https://github.com/2881099/FreeScheduler
10 | https://github.com/2881099/FreeScheduler
11 | git
12 | MIT
13 | IdleScheduler;Scheduler;Timer;TempTask
14 | $(AssemblyName)
15 | $(AssemblyName)
16 | true
17 | true
18 | true
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/IdleBus/IdleBus.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0;net40
5 | 1.5.3
6 | true
7 | YeXiangQin
8 | IdleBus 空闲对象管理容器,有效组织对象重复利用,自动创建、销毁,解决【实例】过多且长时间占用的问题。
9 | https://github.com/2881099/IdleBus
10 | https://github.com/2881099/IdleBus
11 | git
12 | MIT
13 | IdleBus;Idle
14 | $(AssemblyName)
15 | $(AssemblyName)
16 | true
17 | true
18 | true
19 | yxq.snk
20 | false
21 |
22 |
23 |
24 | IdleBus.xml
25 | 3
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/Examples/Examples_IdleBus_Quickstart/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Examples_IdleBus_Quickstart
4 | {
5 | class Program
6 | {
7 | static void Main(string[] args)
8 | {
9 | //超过20秒没有使用,就销毁【实例】
10 | var ib = new IdleBus(TimeSpan.FromSeconds(20));
11 | ib.Notice += (_, e) =>
12 | {
13 | Console.WriteLine(" " + e.Log);
14 |
15 | if (e.NoticeType == IdleBus.NoticeType.AutoRelease)
16 | Console.WriteLine($" [{DateTime.Now.ToString("g")}] {e.Key} 空闲被回收");
17 | };
18 |
19 | while (true)
20 | {
21 | Console.WriteLine("输入 > ");
22 | var line = Console.ReadLine().Trim();
23 | if (string.IsNullOrEmpty(line)) break;
24 |
25 | // 注册
26 | ib.TryRegister(line, () => new TestInfo());
27 |
28 | // 第一次:创建
29 | TestInfo item = ib.Get(line) as TestInfo;
30 |
31 | // 第二次:直接获取,长驻内存直到空闲销毁
32 | item = ib.Get(line) as TestInfo;
33 | }
34 |
35 | ib.Dispose();
36 | }
37 |
38 | class TestInfo : IDisposable
39 | {
40 | public void Dispose() { }
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Examples/Examples_IdleBus_Core31/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Diagnostics;
3 | using System.Threading;
4 |
5 | namespace Examples_IdleBus_Core31
6 | {
7 | class Program
8 | {
9 | static void Main(string[] args)
10 | {
11 | var ib = new IdleBus(TimeSpan.FromSeconds(10));
12 | ib.Notice += (_, e2) =>
13 | {
14 | if (e2.NoticeType == IdleBus.NoticeType.AutoCreate ||
15 | e2.NoticeType == IdleBus.NoticeType.AutoRelease)
16 | {
17 | var log = $"[{DateTime.Now.ToString("HH:mm:ss")}] 线程{Thread.CurrentThread.ManagedThreadId}:{e2.Log}";
18 | //Trace.WriteLine(log);
19 | Console.WriteLine(log);
20 | }
21 | };
22 |
23 | var testkey1 = ib.Exists("key1");
24 |
25 | ib
26 | .Register("key1", () => new ManualResetEvent(false))
27 | .Register("key2", () => new AutoResetEvent(false));
28 |
29 | var testkey2 = ib.Exists("key1");
30 |
31 | for (var a = 3; a < 2000; a++)
32 | ib.Register("key" + a, () => new System.Data.SqlClient.SqlConnection());
33 |
34 | for (var a = 1; a < 2000; a++)
35 | ib.Get("key" + a);
36 |
37 | var now = DateTime.Now;
38 | int counter = 100 * 1000;
39 | for (var k = 0; k < 100; k++)
40 | {
41 | new Thread(() =>
42 | {
43 | var rnd = new Random();
44 |
45 | for (var a = 0; a < 1000; a++)
46 | {
47 | for (var l = 0; l < 10; l++)
48 | {
49 | ib.Get("key" + rnd.Next(1, 2000));
50 | }
51 |
52 | if (Interlocked.Decrement(ref counter) <= 0)
53 | Console.WriteLine($"测试完成,100线程并发 ib.Get() 获取100万次,耗时:{DateTime.Now.Subtract(now).TotalMilliseconds}ms");
54 | }
55 | }).Start();
56 | }
57 |
58 | Console.ReadKey();
59 | ib.Dispose();
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
--------------------------------------------------------------------------------
/Examples/Examples_IdleBus_WinformNet40/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本:4.0.30319.42000
5 | //
6 | // 对此文件的更改可能会导致不正确的行为,并且如果
7 | // 重新生成代码,这些更改将会丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace Examples_IdleBus_WinformNet40.Properties {
12 | using System;
13 |
14 |
15 | ///
16 | /// 一个强类型的资源类,用于查找本地化的字符串等。
17 | ///
18 | // 此类是由 StronglyTypedResourceBuilder
19 | // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
20 | // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
21 | // (以 /str 作为命令选项),或重新生成 VS 项目。
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Resources() {
33 | }
34 |
35 | ///
36 | /// 返回此类使用的缓存的 ResourceManager 实例。
37 | ///
38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
39 | internal static global::System.Resources.ResourceManager ResourceManager {
40 | get {
41 | if (object.ReferenceEquals(resourceMan, null)) {
42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Examples_IdleBus_WinformNet40.Properties.Resources", typeof(Resources).Assembly);
43 | resourceMan = temp;
44 | }
45 | return resourceMan;
46 | }
47 | }
48 |
49 | ///
50 | /// 重写当前线程的 CurrentUICulture 属性
51 | /// 重写当前线程的 CurrentUICulture 属性。
52 | ///
53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
54 | internal static global::System.Globalization.CultureInfo Culture {
55 | get {
56 | return resourceCulture;
57 | }
58 | set {
59 | resourceCulture = value;
60 | }
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/Examples/Examples_IdleBus_WinformNet40/Form1.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Concurrent;
3 | using System.Collections.Generic;
4 | using System.ComponentModel;
5 | using System.Data;
6 | using System.Drawing;
7 | using System.Linq;
8 | using System.Text;
9 | using System.Threading;
10 | using System.Windows.Forms;
11 |
12 | namespace Examples_IdleBus_WinformNet40
13 | {
14 | public partial class Form1 : Form
15 | {
16 | public Form1()
17 | {
18 | InitializeComponent();
19 | }
20 |
21 | private void button1_Click(object sender, EventArgs e)
22 | {
23 | IdleBus.Test();
24 | }
25 |
26 | IdleBus ib;
27 |
28 | private void Form1_Load(object sender, EventArgs e)
29 | {
30 |
31 | }
32 |
33 | private void button4_Click(object sender, EventArgs e)
34 | {
35 | ib?.Dispose();
36 | ib = new IdleBus(TimeSpan.FromSeconds(10));
37 | ib.Notice += (_, e2) =>
38 | {
39 | var log = $"[{DateTime.Now.ToString("HH:mm:ss")}] 线程{Thread.CurrentThread.ManagedThreadId}:{e2.Log}";
40 | //Trace.WriteLine(log);
41 | Console.WriteLine(log);
42 | };
43 |
44 | var key1Val = new ManualResetEvent(false);
45 | ib
46 | .Register("key1", () => key1Val) //姿势错误,第二次创建时会抛出异常
47 | .Register("key2", () => new AutoResetEvent(false));
48 |
49 | for (var a = 3; a < 2000; a++)
50 | ib.Register("key" + a, () => new System.Data.SqlClient.SqlConnection());
51 | }
52 | private void button2_Click(object sender, EventArgs e)
53 | {
54 | label1.Text = ib.Get("key1")?.ToString();
55 | }
56 | private void button3_Click(object sender, EventArgs e)
57 | {
58 | label1.Text = ib.Get("key2")?.ToString();
59 | }
60 |
61 | private void button6_Click(object sender, EventArgs e)
62 | {
63 | var now = DateTime.Now;
64 | int counter = 100 * 1000;
65 | for (var k = 0; k < 100; k++)
66 | {
67 | new Thread(() =>
68 | {
69 | var rnd = new Random();
70 |
71 | for (var a = 0; a < 1000; a++)
72 | {
73 | for (var l = 0; l < 10; l++)
74 | {
75 | ib.Get("key" + rnd.Next(1, 2000));
76 | }
77 |
78 | if (Interlocked.Decrement(ref counter) <= 0)
79 | MessageBox.Show($"测试完成,100线程并发 ib.Get() 获取100万次,耗时:{DateTime.Now.Subtract(now).TotalMilliseconds}ms");
80 | }
81 | }).Start();
82 | }
83 | }
84 |
85 | private void button5_Click(object sender, EventArgs e)
86 | {
87 | ib?.Dispose();
88 | }
89 |
90 |
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/IdleBus/IdleBus`1.ItemInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Concurrent;
3 | using System.Collections.Generic;
4 | using System.Diagnostics;
5 | using System.Text;
6 | using System.Threading;
7 |
8 | partial class IdleBus
9 | {
10 |
11 | class ItemInfo : IDisposable
12 | {
13 | internal IdleBus ib;
14 | internal TKey key;
15 | internal Func create;
16 | internal TimeSpan idle;
17 | internal DateTime createTime;
18 | internal DateTime lastActiveTime;
19 | internal long activeCounter;
20 | internal int releaseErrorCounter;
21 |
22 | internal TValue value { get; private set; }
23 | internal TValue firstValue { get; private set; }
24 | internal bool IsRegisterError { get; private set; }
25 | object valueLock = new object();
26 |
27 | internal TValue GetOrCreate()
28 | {
29 | if (isdisposed == true) return null;
30 | if (value == null)
31 | {
32 | var iscreate = false;
33 | var now = DateTime.Now;
34 | try
35 | {
36 | lock (valueLock)
37 | {
38 | if (isdisposed == true) return null;
39 | if (value == null)
40 | {
41 | value = create();
42 | createTime = DateTime.Now;
43 | Interlocked.Increment(ref ib._usageQuantity);
44 | iscreate = true;
45 | }
46 | else
47 | {
48 | return value;
49 | }
50 | }
51 | if (iscreate)
52 | {
53 | if (value != null)
54 | {
55 | if (firstValue == null) firstValue = value; //记录首次值
56 | else if (firstValue == value) IsRegisterError = true; //第二次与首次相等,注册姿势错误
57 | }
58 | ib.OnNotice(new NoticeEventArgs(NoticeType.AutoCreate, key, null, $"{key} 实例+++创建成功,耗时 {DateTime.Now.Subtract(now).TotalMilliseconds}ms,{ib._usageQuantity}/{ib.Quantity}"));
59 | }
60 | }
61 | catch (Exception ex)
62 | {
63 | ib.OnNotice(new NoticeEventArgs(NoticeType.AutoCreate, key, ex, $"{key} 实例+++创建失败:{ex.Message}"));
64 | throw ex;
65 | }
66 | }
67 | lastActiveTime = DateTime.Now;
68 | Interlocked.Increment(ref activeCounter);
69 | return value;
70 | }
71 |
72 | internal bool Release(Func lockInIf)
73 | {
74 | lock (valueLock)
75 | {
76 | if (value != null && lockInIf())
77 | {
78 | value?.Dispose();
79 | value = null;
80 | Interlocked.Decrement(ref ib._usageQuantity);
81 | Interlocked.Exchange(ref activeCounter, 0);
82 | return true;
83 | }
84 | }
85 | return false;
86 | }
87 |
88 | ~ItemInfo() => Dispose();
89 | bool isdisposed = false;
90 | public void Dispose()
91 | {
92 | if (isdisposed) return;
93 | lock (valueLock)
94 | {
95 | if (isdisposed) return;
96 | isdisposed = true;
97 | }
98 | try
99 | {
100 | Release(() => true);
101 | }
102 | catch { }
103 | }
104 |
105 | }
106 |
107 | }
--------------------------------------------------------------------------------
/Examples/Examples_IdleBus_WinformNet40/Examples_IdleBus_WinformNet40.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {0FC8305A-114E-4792-9226-726FE3651CB0}
8 | WinExe
9 | Examples_IdleBus_WinformNet40
10 | Examples_IdleBus_WinformNet40
11 | v4.0
12 | 512
13 | true
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 | Form
49 |
50 |
51 | Form1.cs
52 |
53 |
54 |
55 |
56 | Form1.cs
57 |
58 |
59 | ResXFileCodeGenerator
60 | Resources.Designer.cs
61 | Designer
62 |
63 |
64 | True
65 | Resources.resx
66 | True
67 |
68 |
69 | SettingsSingleFileGenerator
70 | Settings.Designer.cs
71 |
72 |
73 | True
74 | Settings.settings
75 | True
76 |
77 |
78 |
79 |
80 | {ab044be0-8676-481f-a454-3ad68b8bbe54}
81 | IdleBus
82 |
83 |
84 |
85 |
--------------------------------------------------------------------------------
/IdleBus.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.0.31903.59
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IdleBus", "IdleBus\IdleBus.csproj", "{AB044BE0-8676-481F-A454-3AD68B8BBE54}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docs", "Docs", "{D820DCDF-5AE7-4B8E-9D1F-A5DDE89AFD7C}"
9 | ProjectSection(SolutionItems) = preProject
10 | readme.md = readme.md
11 | EndProjectSection
12 | EndProject
13 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IdleScheduler", "IdleScheduler\IdleScheduler.csproj", "{3BF4F6C3-CD28-4795-987F-36A1AAAFD399}"
14 | EndProject
15 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Examples", "Examples", "{0832562A-80F3-4513-AC2F-4B4DFBB04F57}"
16 | EndProject
17 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Examples_IdleBus_Core31", "Examples\Examples_IdleBus_Core31\Examples_IdleBus_Core31.csproj", "{A040B309-F980-43EF-B62F-0EDA2D031DA2}"
18 | EndProject
19 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Examples_IdleBus_WinformNet40", "Examples\Examples_IdleBus_WinformNet40\Examples_IdleBus_WinformNet40.csproj", "{0FC8305A-114E-4792-9226-726FE3651CB0}"
20 | EndProject
21 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Examples_IdleBus_Quickstart", "Examples\Examples_IdleBus_Quickstart\Examples_IdleBus_Quickstart.csproj", "{D359491B-5B34-408F-84A1-A3646A74BF54}"
22 | EndProject
23 | Global
24 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
25 | Debug|Any CPU = Debug|Any CPU
26 | Release|Any CPU = Release|Any CPU
27 | EndGlobalSection
28 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
29 | {AB044BE0-8676-481F-A454-3AD68B8BBE54}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
30 | {AB044BE0-8676-481F-A454-3AD68B8BBE54}.Debug|Any CPU.Build.0 = Debug|Any CPU
31 | {AB044BE0-8676-481F-A454-3AD68B8BBE54}.Release|Any CPU.ActiveCfg = Release|Any CPU
32 | {AB044BE0-8676-481F-A454-3AD68B8BBE54}.Release|Any CPU.Build.0 = Release|Any CPU
33 | {3BF4F6C3-CD28-4795-987F-36A1AAAFD399}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
34 | {3BF4F6C3-CD28-4795-987F-36A1AAAFD399}.Debug|Any CPU.Build.0 = Debug|Any CPU
35 | {3BF4F6C3-CD28-4795-987F-36A1AAAFD399}.Release|Any CPU.ActiveCfg = Release|Any CPU
36 | {3BF4F6C3-CD28-4795-987F-36A1AAAFD399}.Release|Any CPU.Build.0 = Release|Any CPU
37 | {A040B309-F980-43EF-B62F-0EDA2D031DA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
38 | {A040B309-F980-43EF-B62F-0EDA2D031DA2}.Debug|Any CPU.Build.0 = Debug|Any CPU
39 | {A040B309-F980-43EF-B62F-0EDA2D031DA2}.Release|Any CPU.ActiveCfg = Release|Any CPU
40 | {A040B309-F980-43EF-B62F-0EDA2D031DA2}.Release|Any CPU.Build.0 = Release|Any CPU
41 | {0FC8305A-114E-4792-9226-726FE3651CB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
42 | {0FC8305A-114E-4792-9226-726FE3651CB0}.Debug|Any CPU.Build.0 = Debug|Any CPU
43 | {0FC8305A-114E-4792-9226-726FE3651CB0}.Release|Any CPU.ActiveCfg = Release|Any CPU
44 | {0FC8305A-114E-4792-9226-726FE3651CB0}.Release|Any CPU.Build.0 = Release|Any CPU
45 | {D359491B-5B34-408F-84A1-A3646A74BF54}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
46 | {D359491B-5B34-408F-84A1-A3646A74BF54}.Debug|Any CPU.Build.0 = Debug|Any CPU
47 | {D359491B-5B34-408F-84A1-A3646A74BF54}.Release|Any CPU.ActiveCfg = Release|Any CPU
48 | {D359491B-5B34-408F-84A1-A3646A74BF54}.Release|Any CPU.Build.0 = Release|Any CPU
49 | EndGlobalSection
50 | GlobalSection(SolutionProperties) = preSolution
51 | HideSolutionNode = FALSE
52 | EndGlobalSection
53 | GlobalSection(NestedProjects) = preSolution
54 | {A040B309-F980-43EF-B62F-0EDA2D031DA2} = {0832562A-80F3-4513-AC2F-4B4DFBB04F57}
55 | {0FC8305A-114E-4792-9226-726FE3651CB0} = {0832562A-80F3-4513-AC2F-4B4DFBB04F57}
56 | {D359491B-5B34-408F-84A1-A3646A74BF54} = {0832562A-80F3-4513-AC2F-4B4DFBB04F57}
57 | EndGlobalSection
58 | GlobalSection(ExtensibilityGlobals) = postSolution
59 | SolutionGuid = {23CB00AF-59EE-4479-A279-0A3AECA31FF5}
60 | EndGlobalSection
61 | EndGlobal
62 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | IdleBus 空闲对象管理容器,有效组织对象重复利用,自动创建、销毁,解决【实例】过多且长时间占用的问题。有时候想做一个单例对象重复使用提升性能,但是定义多了,有的又可能一直空闲着占用资源。
2 |
3 | 专门解决:又想重复利用,又想少占资源的场景。
4 |
5 | ## 快速开始
6 |
7 | > dotnet add package IdleBus
8 |
9 | ```csharp
10 | class Program
11 | {
12 | static void Main(string[] args)
13 | {
14 | //超过20秒没有使用,就销毁【实例】
15 | var ib = new IdleBus(TimeSpan.FromSeconds(20));
16 | ib.Notice += (_, e) =>
17 | {
18 | Console.WriteLine(" " + e.Log);
19 |
20 | if (e.NoticeType == IdleBus.NoticeType.AutoRelease)
21 | Console.WriteLine($" [{DateTime.Now.ToString("g")}] {e.Key} 空闲被回收");
22 | };
23 |
24 | while (true)
25 | {
26 | Console.WriteLine("输入 > ");
27 | var line = Console.ReadLine().Trim();
28 | if (string.IsNullOrEmpty(line)) break;
29 |
30 | // 注册
31 | ib.TryRegister(line, () => new TestInfo());
32 |
33 | // 第一次:创建
34 | TestInfo item = ib.Get(line) as TestInfo;
35 |
36 | // 第二次:直接获取,长驻内存直到空闲销毁
37 | item = ib.Get(line) as TestInfo;
38 | }
39 |
40 | ib.Dispose();
41 | }
42 |
43 | class TestInfo : IDisposable
44 | {
45 | public void Dispose() { }
46 | }
47 | }
48 | ```
49 |
50 | 输出:
51 |
52 | ```shell
53 | 输入 >
54 | aa1
55 | aa1 注册成功,0/1
56 | aa1 实例+++创建成功,耗时 0.1658ms,1/1
57 | aa1 实例获取成功 1次
58 | aa1 实例获取成功 2次
59 | 输入 >
60 | aa2
61 | aa2 注册成功,1/2
62 | aa2 实例+++创建成功,耗时 0.0065ms,2/2
63 | aa2 实例获取成功 1次
64 | aa2 实例获取成功 2次
65 | 输入 >
66 | aa3
67 | aa3 注册成功,2/3
68 | aa3 实例+++创建成功,耗时 0.0073ms,3/3
69 | aa3 实例获取成功 1次
70 | aa3 实例获取成功 2次
71 | 输入 >
72 | aa1 ---自动释放成功,耗时 0.7607ms,2/3
73 | [2020/1/7 14:22] aa1 空闲被回收
74 | aa2 ---自动释放成功,耗时 0.0289ms,1/3
75 | [2020/1/7 14:22] aa2 空闲被回收
76 | aa3 ---自动释放成功,耗时 0.0046ms,0/3
77 | [2020/1/7 14:22] aa3 空闲被回收
78 | ```
79 |
80 | ## API
81 |
82 | new IdleBus 可使用任何 IDisposable 实现类【混合注入】
83 |
84 | new IdleBus\ 可【自定义类型】注入,如: new IdleBus\()
85 |
86 | | Method | 说明 |
87 | | -- | -- |
88 | | void Ctor() | 创建空闲容器 |
89 | | void Ctor(TimeSpan idle) | 指定空闲时间,创建空闲容器 |
90 | | IdleBus Register(string key, Func\ create) | 注册(其类型必须实现 IDisposable) |
91 | | IdleBus Register(string key, Func\ create, TimeSpan idle) | 注册,单独设置空间时间 |
92 | | T Get(string key) | 获取【实例】(线程安全),key 未注册时,抛出异常 |
93 | | List\ GetAll() | 获得所有【实例】(线程安全) |
94 | | bool Exists(string key) | 判断 key 是否已注册 |
95 | | void Remove(string key) | 删除已注册的 |
96 | | int Quantity | 注册数量 |
97 | | int UsageQuantity | 已创建【实例】数量 |
98 | | event Notice | 容器内部的变化通知,如:自动释放、自动创建 |
99 |
100 | > 注意:Register 参数 create 属于对象创建器,切莫直接返回外部创建好的对象
101 |
102 | ```csharp
103 | var obj = new Xxx();
104 | ib.Register("key01", () => obj); //错了,错了,错了
105 |
106 | ib.Register("key01", () => new Xxx()); //正确
107 | ```
108 |
109 | ## 设计思路
110 |
111 | IdleBus 和对象池不同,对象池是队列设计,我们是 KV 设计。
112 |
113 | IdleBus 又像缓存,又像池,又像容器,无法具体描述。
114 |
115 | 1、注册:向容器中注册对象,指定 key + 创建器 + 空闲时间,可以注册和管理任何实现 IDisposable 接口对象
116 |
117 | 2、获取对象:开发人员使用 key 作为参数调用方法获得对象
118 |
119 | - 存在时,直接返回
120 | - 不存在时,创建对象(保证线程安全)
121 |
122 | 3、过期销毁:当容器中有实例运行,会启用后台线程定时检查,超过空闲时间设置的将被释放(Dispose)
123 |
124 | ## 使用场景
125 |
126 | - 多租户按数据库区分的场景,假设有1000个租户;
127 | - Redis 客户端需要操作 N 个 服务器;
128 | - Socket 长连接闲置后自动释放;
129 | - 管理 1000个 rabbitmq 服务器的客户端;
130 | - [IdleScheduler](https://github.com/2881099/IdleBus/tree/master/IdleScheduler) 利用 IdleBus 实现的轻量定时任务调度;
131 | - 等等等。。。
132 |
133 | 举例:向 1000个 (不同的、不同的、不同的) rabbitmq 服务器发送消息,正常有两种做法:
134 |
135 | 1、定义 1000 个静态 client 一直 open 着,重复利用
136 |
137 | 缺点:1000个里面不是每个都活跃,然后也一直占用着资源
138 |
139 | 2、每次发送消息的时候 open,使用完再 close
140 |
141 | ```csharp
142 | new client("mq_0001server").pub(...).close();
143 | new client("mq_0002server").pub(...).close();
144 | new client("mq_0003server").pub(...).close();
145 | new client("mq_0004server").pub(...).close();
146 | ```
147 |
148 | 缺点:性能损耗会比较大,socket 没有有效的重复利用
149 |
--------------------------------------------------------------------------------
/IdleBus/IdleBus`1.ThreadScan.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Concurrent;
3 | using System.Collections.Generic;
4 | using System.Diagnostics;
5 | using System.Linq;
6 | using System.Text;
7 | using System.Threading;
8 |
9 | partial class IdleBus
10 | {
11 | bool _threadStarted = false;
12 | object _threadStartedLock = new object();
13 |
14 | void ThreadScanWatch(ItemInfo item)
15 | {
16 | var startThread = false;
17 | if (_threadStarted == false)
18 | lock (_threadStartedLock)
19 | if (_threadStarted == false)
20 | startThread = _threadStarted = true;
21 |
22 | if (startThread)
23 | new Thread(() =>
24 | {
25 | this.ThreadScanWatchHandler();
26 | lock (_threadStartedLock)
27 | _threadStarted = false;
28 | }).Start();
29 | }
30 |
31 |
32 | public class TimeoutScanOptions
33 | {
34 | ///
35 | /// 扫描线程间隔(默认值:2秒)
36 | ///
37 | public TimeSpan Interval { get; set; } = TimeSpan.FromSeconds(2);
38 | ///
39 | /// 扫描线程空闲多少秒退出(默认值:10秒)
40 | ///
41 | public int QuitWaitSeconds { get; set; } = 10;
42 | ///
43 | /// 扫描的每批数量(默认值:512)
44 | /// 可防止注册数量太多时导致 CPU 占用过高
45 | ///
46 | public int BatchQuantity { get; set; } = 512;
47 | ///
48 | /// 达到扫描的每批数量时,线程等待(默认值:1秒)
49 | ///
50 | public TimeSpan BatchQuantityWait { get; set; } = TimeSpan.FromSeconds(1);
51 | }
52 | ///
53 | /// 扫描过期对象的设置
54 | /// 机制:当窗口里有存活对象时,扫描线程才会开启(只开启一个线程)。
55 | /// 连续多少秒都没存活的对象时,才退出扫描。
56 | ///
57 | public TimeoutScanOptions ScanOptions { get; } = new TimeoutScanOptions();
58 |
59 | void ThreadScanWatchHandler()
60 | {
61 | var couter = 0;
62 | while (IsDisposed == false)
63 | {
64 | if (ThreadJoin(ScanOptions.Interval) == false) return;
65 | this.InternalRemoveDelayHandler();
66 |
67 | if (_usageQuantity == 0)
68 | {
69 | couter = couter + (int)ScanOptions.Interval.TotalSeconds;
70 | if (couter < ScanOptions.QuitWaitSeconds) continue;
71 | break;
72 | }
73 | couter = 0;
74 |
75 | var keys = _dic.Keys.ToArray();
76 | long keysIndex = 0;
77 | foreach (var key in keys)
78 | {
79 | if (IsDisposed) return;
80 | ++keysIndex;
81 | if (ScanOptions.BatchQuantity > 0 && keysIndex % ScanOptions.BatchQuantity == 0)
82 | {
83 | if (ThreadJoin(ScanOptions.BatchQuantityWait) == false) return;
84 | }
85 |
86 | if (_dic.TryGetValue(key, out var item) == false) continue;
87 | if (item.value == null) continue;
88 | if (DateTime.Now.Subtract(item.lastActiveTime) <= item.idle) continue;
89 | try
90 | {
91 | var now = DateTime.Now;
92 | if (item.Release(() => DateTime.Now.Subtract(item.lastActiveTime) > item.idle && item.lastActiveTime >= item.createTime))
93 | //防止并发有其他线程创建,最后活动时间 > 创建时间
94 | this.OnNotice(new NoticeEventArgs(NoticeType.AutoRelease, item.key, null, $"{key} ---自动释放成功,耗时 {DateTime.Now.Subtract(now).TotalMilliseconds}ms,{_usageQuantity}/{Quantity}"));
95 | }
96 | catch (Exception ex)
97 | {
98 | this.OnNotice(new NoticeEventArgs(NoticeType.AutoRelease, item.key, ex, $"{key} ---自动释放执行出错:{ex.Message}"));
99 | }
100 | }
101 | }
102 | }
103 |
104 | bool ThreadJoin(TimeSpan interval)
105 | {
106 | if (interval <= TimeSpan.Zero) return true;
107 | var milliseconds = interval.TotalMilliseconds;
108 | var seconds = Math.Floor(milliseconds / 1000);
109 | milliseconds = milliseconds - seconds * 1000;
110 |
111 | for (var a = 0; a < seconds; a++)
112 | {
113 | Thread.CurrentThread.Join(TimeSpan.FromSeconds(1));
114 | if (IsDisposed) return false;
115 | }
116 | for (var a = 0; a < milliseconds; a += 200)
117 | {
118 | Thread.CurrentThread.Join(TimeSpan.FromMilliseconds(200));
119 | if (IsDisposed) return false;
120 | }
121 | return true;
122 | }
123 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | [Xx]64/
19 | [Xx]86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 |
24 | # Visual Studio 2015 cache/options directory
25 | .vs/
26 | # Uncomment if you have tasks that create the project's static files in wwwroot
27 | #wwwroot/
28 |
29 | # MSTest test Results
30 | [Tt]est[Rr]esult*/
31 | [Bb]uild[Ll]og.*
32 |
33 | # NUNIT
34 | *.VisualState.xml
35 | TestResult.xml
36 |
37 | # Build Results of an ATL Project
38 | [Dd]ebugPS/
39 | [Rr]eleasePS/
40 | dlldata.c
41 |
42 | # DNX
43 | project.lock.json
44 | package-lock.json
45 | artifacts/
46 |
47 | *_i.c
48 | *_p.c
49 | *_i.h
50 | *.ilk
51 | *.meta
52 | *.obj
53 | *.pch
54 | *.pdb
55 | *.pgc
56 | *.pgd
57 | *.rsp
58 | *.sbr
59 | *.tlb
60 | *.tli
61 | *.tlh
62 | *.tmp
63 | *.tmp_proj
64 | *.log
65 | *.vspscc
66 | *.vssscc
67 | .builds
68 | *.pidb
69 | *.svclog
70 | *.scc
71 |
72 | # Chutzpah Test files
73 | _Chutzpah*
74 |
75 | # Visual C++ cache files
76 | ipch/
77 | *.aps
78 | *.ncb
79 | *.opendb
80 | *.opensdf
81 | *.sdf
82 | *.cachefile
83 | *.VC.db
84 |
85 | # Visual Studio profiler
86 | *.psess
87 | *.vsp
88 | *.vspx
89 | *.sap
90 |
91 | # TFS 2012 Local Workspace
92 | $tf/
93 |
94 | # Guidance Automation Toolkit
95 | *.gpState
96 |
97 | # ReSharper is a .NET coding add-in
98 | _ReSharper*/
99 | *.[Rr]e[Ss]harper
100 | *.DotSettings.user
101 |
102 | # JustCode is a .NET coding add-in
103 | .JustCode
104 |
105 | # TeamCity is a build add-in
106 | _TeamCity*
107 |
108 | # DotCover is a Code Coverage Tool
109 | *.dotCover
110 |
111 | # NCrunch
112 | _NCrunch_*
113 | .*crunch*.local.xml
114 | nCrunchTemp_*
115 |
116 | # MightyMoose
117 | *.mm.*
118 | AutoTest.Net/
119 |
120 | # Web workbench (sass)
121 | .sass-cache/
122 |
123 | # Installshield output folder
124 | [Ee]xpress/
125 |
126 | # DocProject is a documentation generator add-in
127 | DocProject/buildhelp/
128 | DocProject/Help/*.HxT
129 | DocProject/Help/*.HxC
130 | DocProject/Help/*.hhc
131 | DocProject/Help/*.hhk
132 | DocProject/Help/*.hhp
133 | DocProject/Help/Html2
134 | DocProject/Help/html
135 |
136 | # Click-Once directory
137 | publish/
138 |
139 | # Publish Web Output
140 | *.[Pp]ublish.xml
141 | *.azurePubxml
142 |
143 | # TODO: Un-comment the next line if you do not want to checkin
144 | # your web deploy settings because they may include unencrypted
145 | # passwords
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # NuGet Packages
150 | *.nupkg
151 | # The packages folder can be ignored because of Package Restore
152 | **/packages/*
153 | # except build/, which is used as an MSBuild target.
154 | !**/packages/build/
155 | # Uncomment if necessary however generally it will be regenerated when needed
156 | #!**/packages/repositories.config
157 | # NuGet v3's project.json files produces more ignoreable files
158 | *.nuget.props
159 | *.nuget.targets
160 |
161 | # Microsoft Azure Build Output
162 | csx/
163 | *.build.csdef
164 |
165 | # Microsoft Azure Emulator
166 | ecf/
167 | rcf/
168 |
169 | # Microsoft Azure ApplicationInsights config file
170 | ApplicationInsights.config
171 |
172 | # Windows Store app package directory
173 | AppPackages/
174 | BundleArtifacts/
175 |
176 | # Visual Studio cache files
177 | # files ending in .cache can be ignored
178 | *.[Cc]ache
179 | # but keep track of directories ending in .cache
180 | !*.[Cc]ache/
181 |
182 | # Others
183 | ClientBin/
184 | [Ss]tyle[Cc]op.*
185 | ~$*
186 | *~
187 | *.dbmdl
188 | *.dbproj.schemaview
189 | *.pfx
190 | *.publishsettings
191 | node_modules/
192 | orleans.codegen.cs
193 |
194 | # RIA/Silverlight projects
195 | Generated_Code/
196 |
197 | # Backup & report files from converting an old project file
198 | # to a newer Visual Studio version. Backup files are not needed,
199 | # because we have git ;-)
200 | _UpgradeReport_Files/
201 | Backup*/
202 | UpgradeLog*.XML
203 | UpgradeLog*.htm
204 |
205 | # SQL Server files
206 | *.mdf
207 | *.ldf
208 |
209 | # Business Intelligence projects
210 | *.rdl.data
211 | *.bim.layout
212 | *.bim_*.settings
213 |
214 | # Microsoft Fakes
215 | FakesAssemblies/
216 |
217 | # GhostDoc plugin setting file
218 | *.GhostDoc.xml
219 |
220 | # Node.js Tools for Visual Studio
221 | .ntvs_analysis.dat
222 |
223 | # Visual Studio 6 build log
224 | *.plg
225 |
226 | # Visual Studio 6 workspace options file
227 | *.opt
228 |
229 | # Visual Studio LightSwitch build output
230 | **/*.HTMLClient/GeneratedArtifacts
231 | **/*.DesktopClient/GeneratedArtifacts
232 | **/*.DesktopClient/ModelManifest.xml
233 | **/*.Server/GeneratedArtifacts
234 | **/*.Server/ModelManifest.xml
235 | _Pvt_Extensions
236 |
237 | # LightSwitch generated files
238 | GeneratedArtifacts/
239 | ModelManifest.xml
240 |
241 | # Paket dependency manager
242 | .paket/paket.exe
243 |
244 | # FAKE - F# Make
245 | .fake/
--------------------------------------------------------------------------------
/IdleBus/IdleBus.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | IdleBus
5 |
6 |
7 |
8 |
9 | 空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题
10 |
11 |
12 |
13 |
14 | 按空闲时间1分钟,创建空闲容器
15 |
16 |
17 |
18 |
19 | 指定空闲时间、创建空闲容器
20 |
21 | 空闲时间
22 |
23 |
24 |
25 | 空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题
26 |
27 |
28 |
29 |
30 | 按空闲时间1分钟,创建空闲容器
31 |
32 |
33 |
34 |
35 | 指定空闲时间、创建空闲容器
36 |
37 | 空闲时间
38 |
39 |
40 |
41 | 空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题
42 |
43 |
44 |
45 |
46 | 按空闲时间1分钟,创建空闲容器
47 |
48 |
49 |
50 |
51 | 指定空闲时间、创建空闲容器
52 |
53 | 空闲时间
54 |
55 |
56 |
57 | 根据 key 获得或创建【实例】(线程安全)
58 | key 未注册时,抛出异常
59 |
60 |
61 |
62 |
63 |
64 |
65 | 获得或创建所有【实例】(线程安全)
66 |
67 |
68 |
69 |
70 |
71 | 获得所有已注册的 key(线程安全)
72 |
73 |
74 |
75 |
76 |
77 | 判断 key 是否注册
78 |
79 |
80 |
81 |
82 |
83 |
84 | 注册【实例】
85 |
86 |
87 | 实例创建方法
88 |
89 |
90 |
91 |
92 | 已创建【实例】数量
93 |
94 |
95 |
96 |
97 | 注册数量
98 |
99 |
100 |
101 |
102 | 通知事件
103 |
104 |
105 |
106 |
107 | 执行 Register 方法的时候
108 |
109 |
110 |
111 |
112 | 执行 Remove 方法的时候,注意:实际会延时释放【实例】
113 |
114 |
115 |
116 |
117 | 自动创建【实例】的时候
118 |
119 |
120 |
121 |
122 | 自动释放不活跃【实例】的时候
123 |
124 |
125 |
126 |
127 | 获取【实例】的时候
128 |
129 |
130 |
131 |
132 | 扫描线程间隔(默认值:2秒)
133 |
134 |
135 |
136 |
137 | 扫描线程空闲多少秒退出(默认值:10秒)
138 |
139 |
140 |
141 |
142 | 扫描的每批数量(默认值:512)
143 | 可防止注册数量太多时导致 CPU 占用过高
144 |
145 |
146 |
147 |
148 | 达到扫描的每批数量时,线程等待(默认值:1秒)
149 |
150 |
151 |
152 |
153 | 扫描过期对象的设置
154 | 机制:当窗口里有存活对象时,扫描线程才会开启(只开启一个线程)。
155 | 连续多少秒都没存活的对象时,才退出扫描。
156 |
157 |
158 |
159 |
160 |
--------------------------------------------------------------------------------
/Examples/Examples_IdleBus_WinformNet40/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | text/microsoft-resx
107 |
108 |
109 | 2.0
110 |
111 |
112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
113 |
114 |
115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
--------------------------------------------------------------------------------
/Examples/Examples_IdleBus_WinformNet40/Form1.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
--------------------------------------------------------------------------------
/Examples/Examples_IdleBus_WinformNet40/Form1.Designer.cs:
--------------------------------------------------------------------------------
1 | namespace Examples_IdleBus_WinformNet40
2 | {
3 | partial class Form1
4 | {
5 | ///
6 | /// 必需的设计器变量。
7 | ///
8 | private System.ComponentModel.IContainer components = null;
9 |
10 | ///
11 | /// 清理所有正在使用的资源。
12 | ///
13 | /// 如果应释放托管资源,为 true;否则为 false。
14 | protected override void Dispose(bool disposing)
15 | {
16 | if (disposing && (components != null))
17 | {
18 | components.Dispose();
19 | }
20 | base.Dispose(disposing);
21 | }
22 |
23 | #region Windows 窗体设计器生成的代码
24 |
25 | ///
26 | /// 设计器支持所需的方法 - 不要修改
27 | /// 使用代码编辑器修改此方法的内容。
28 | ///
29 | private void InitializeComponent()
30 | {
31 | this.button1 = new System.Windows.Forms.Button();
32 | this.button2 = new System.Windows.Forms.Button();
33 | this.button3 = new System.Windows.Forms.Button();
34 | this.button4 = new System.Windows.Forms.Button();
35 | this.button5 = new System.Windows.Forms.Button();
36 | this.label1 = new System.Windows.Forms.Label();
37 | this.button6 = new System.Windows.Forms.Button();
38 | this.SuspendLayout();
39 | //
40 | // button1
41 | //
42 | this.button1.Location = new System.Drawing.Point(53, 119);
43 | this.button1.Name = "button1";
44 | this.button1.Size = new System.Drawing.Size(138, 23);
45 | this.button1.TabIndex = 0;
46 | this.button1.Text = "IdleBus.Test()";
47 | this.button1.UseVisualStyleBackColor = true;
48 | this.button1.Click += new System.EventHandler(this.button1_Click);
49 | //
50 | // button2
51 | //
52 | this.button2.Location = new System.Drawing.Point(147, 271);
53 | this.button2.Name = "button2";
54 | this.button2.Size = new System.Drawing.Size(183, 23);
55 | this.button2.TabIndex = 1;
56 | this.button2.Text = "IdleBus.Get(key1)";
57 | this.button2.UseVisualStyleBackColor = true;
58 | this.button2.Click += new System.EventHandler(this.button2_Click);
59 | //
60 | // button3
61 | //
62 | this.button3.Location = new System.Drawing.Point(147, 300);
63 | this.button3.Name = "button3";
64 | this.button3.Size = new System.Drawing.Size(183, 23);
65 | this.button3.TabIndex = 2;
66 | this.button3.Text = "IdleBus.Get(key2)";
67 | this.button3.UseVisualStyleBackColor = true;
68 | this.button3.Click += new System.EventHandler(this.button3_Click);
69 | //
70 | // button4
71 | //
72 | this.button4.Location = new System.Drawing.Point(147, 230);
73 | this.button4.Name = "button4";
74 | this.button4.Size = new System.Drawing.Size(183, 23);
75 | this.button4.TabIndex = 3;
76 | this.button4.Text = "new IdleBus()";
77 | this.button4.UseVisualStyleBackColor = true;
78 | this.button4.Click += new System.EventHandler(this.button4_Click);
79 | //
80 | // button5
81 | //
82 | this.button5.Location = new System.Drawing.Point(147, 408);
83 | this.button5.Name = "button5";
84 | this.button5.Size = new System.Drawing.Size(183, 23);
85 | this.button5.TabIndex = 4;
86 | this.button5.Text = "IdleBus.Dispose()";
87 | this.button5.UseVisualStyleBackColor = true;
88 | this.button5.Click += new System.EventHandler(this.button5_Click);
89 | //
90 | // label1
91 | //
92 | this.label1.AutoSize = true;
93 | this.label1.Font = new System.Drawing.Font("宋体", 15F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
94 | this.label1.Location = new System.Drawing.Point(400, 289);
95 | this.label1.Name = "label1";
96 | this.label1.Size = new System.Drawing.Size(75, 20);
97 | this.label1.TabIndex = 5;
98 | this.label1.Text = "label1";
99 | //
100 | // button6
101 | //
102 | this.button6.Location = new System.Drawing.Point(147, 329);
103 | this.button6.Name = "button6";
104 | this.button6.Size = new System.Drawing.Size(183, 23);
105 | this.button6.TabIndex = 6;
106 | this.button6.Text = "IdleBus.Get Concurrent";
107 | this.button6.UseVisualStyleBackColor = true;
108 | this.button6.Click += new System.EventHandler(this.button6_Click);
109 | //
110 | // Form1
111 | //
112 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
113 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
114 | this.ClientSize = new System.Drawing.Size(800, 450);
115 | this.Controls.Add(this.button6);
116 | this.Controls.Add(this.label1);
117 | this.Controls.Add(this.button5);
118 | this.Controls.Add(this.button4);
119 | this.Controls.Add(this.button3);
120 | this.Controls.Add(this.button2);
121 | this.Controls.Add(this.button1);
122 | this.Name = "Form1";
123 | this.Text = "Form1";
124 | this.Load += new System.EventHandler(this.Form1_Load);
125 | this.ResumeLayout(false);
126 | this.PerformLayout();
127 |
128 | }
129 |
130 | #endregion
131 |
132 | private System.Windows.Forms.Button button1;
133 | private System.Windows.Forms.Button button2;
134 | private System.Windows.Forms.Button button3;
135 | private System.Windows.Forms.Button button4;
136 | private System.Windows.Forms.Button button5;
137 | private System.Windows.Forms.Label label1;
138 | private System.Windows.Forms.Button button6;
139 | }
140 | }
141 |
142 |
--------------------------------------------------------------------------------
/IdleBus/IdleBus`1.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Concurrent;
3 | using System.Collections.Generic;
4 | using System.Diagnostics;
5 | using System.Linq;
6 | using System.Text;
7 | using System.Threading;
8 |
9 | ///
10 | /// 空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题
11 | ///
12 | public partial class IdleBus : IDisposable where TValue : class, IDisposable
13 | {
14 |
15 | ConcurrentDictionary _dic;
16 | ConcurrentDictionary _removePending;
17 | object _usageLock = new object();
18 | int _usageQuantity;
19 | TimeSpan _defaultIdle;
20 |
21 | ///
22 | /// 按空闲时间1分钟,创建空闲容器
23 | ///
24 | public IdleBus() : this(TimeSpan.FromMinutes(1)) { }
25 |
26 | ///
27 | /// 指定空闲时间、创建空闲容器
28 | ///
29 | /// 空闲时间
30 | public IdleBus(TimeSpan idle)
31 | {
32 | _dic = new ConcurrentDictionary();
33 | _removePending = new ConcurrentDictionary();
34 | _usageQuantity = 0;
35 | _defaultIdle = idle;
36 | }
37 |
38 | ///
39 | /// 根据 key 获得或创建【实例】(线程安全)
40 | /// key 未注册时,抛出异常
41 | ///
42 | ///
43 | ///
44 | public TValue Get(TKey key)
45 | {
46 | if (IsDisposed) throw new Exception($"{key} 实例获取失败,{nameof(IdleBus)} 对象已释放");
47 | if (_dic.TryGetValue(key, out var item) == false)
48 | {
49 | var error = new Exception($"{key} 实例获取失败,因为没有注册");
50 | this.OnNotice(new NoticeEventArgs(NoticeType.Get, key, error, error.Message));
51 | throw error;
52 | }
53 |
54 | var now = DateTime.Now;
55 | var ret = item.GetOrCreate();
56 | if (item.IsRegisterError)
57 | {
58 | this.OnNotice(new NoticeEventArgs(NoticeType.Get, key, null, $"{key} 实例获取失败:检测到注册实例的参数 create 返回了相同的实例,应该每次返回新实例,正确:() => new Xxx(),错误:() => 变量"));
59 | throw new ArgumentException($"{key} 实例获取失败:检测到注册实例的参数 create 返回了相同的实例,应该每次返回新实例,正确:() => new Xxx(),错误:() => 变量");
60 | }
61 | var tsms = DateTime.Now.Subtract(now).TotalMilliseconds;
62 | this.OnNotice(new NoticeEventArgs(NoticeType.Get, key, null, $"{key} 实例获取成功 {item.activeCounter}次{(tsms > 5 ? $",耗时 {tsms}ms" : "")}"));
63 | //this.ThreadLiveWatch(item); //这种模式采用 Sorted 性能会比较慢
64 | this.ThreadScanWatch(item); //这种在后台扫描 _dic,定时要求可能没那么及时
65 | return ret;
66 | }
67 |
68 | ///
69 | /// 获得或创建所有【实例】(线程安全)
70 | ///
71 | ///
72 | public List GetAll() => _dic.Keys.ToArray().Select(a => Get(a)).ToList();
73 |
74 | ///
75 | /// 获得所有已注册的 key(线程安全)
76 | ///
77 | ///
78 | public TKey[] GetKeys(Func filter = null)
79 | {
80 | if (filter == null) return _dic.Keys.ToArray();
81 | return _dic.Keys.ToArray().Where(key => _dic.TryGetValue(key, out var item) && filter(item.value)).ToArray();
82 | }
83 |
84 | ///
85 | /// 判断 key 是否注册
86 | ///
87 | ///
88 | ///
89 | public bool Exists(TKey key)
90 | {
91 | if (key == null) return false;
92 | return _dic.ContainsKey(key);
93 | }
94 |
95 | ///
96 | /// 注册【实例】
97 | ///
98 | ///
99 | /// 实例创建方法
100 | ///
101 | public IdleBus Register(TKey key, Func create)
102 | {
103 | InternalRegister(key, create, null, true);
104 | return this;
105 | }
106 | public IdleBus Register(TKey key, Func create, TimeSpan idle)
107 | {
108 | InternalRegister(key, create, idle, true);
109 | return this;
110 | }
111 | public bool TryRegister(TKey key, Func create) => InternalRegister(key, create, null, false);
112 | public bool TryRegister(TKey key, Func create, TimeSpan idle) => InternalRegister(key, create, idle, false);
113 |
114 | public bool TryRemove(TKey key, bool now = false) => InternalRemove(key, now, false);
115 |
116 | ///
117 | /// 已创建【实例】数量
118 | ///
119 | public int UsageQuantity => _usageQuantity;
120 | ///
121 | /// 注册数量
122 | ///
123 | public int Quantity => _dic.Count;
124 | ///
125 | /// 通知事件
126 | ///
127 | public event EventHandler Notice;
128 |
129 | bool InternalRegister(TKey key, Func create, TimeSpan? idle, bool isThrow)
130 | {
131 | if (IsDisposed)
132 | {
133 | if (isThrow) throw new Exception($"{key} 注册失败,{nameof(IdleBus)} 对象已释放");
134 | return false;
135 | }
136 | var error = new Exception($"{key} 注册失败,请勿重复注册");
137 | if (_dic.ContainsKey(key))
138 | {
139 | this.OnNotice(new NoticeEventArgs(NoticeType.Register, key, error, error.Message));
140 | if (isThrow) throw error;
141 | return false;
142 | }
143 |
144 | if (idle == null) idle = _defaultIdle;
145 | //if (idle < TimeSpan.FromSeconds(5))
146 | //{
147 | // var limitError = new Exception($"{key} 注册失败,{nameof(idle)} 参数必须 >= 5秒");
148 | // this.OnNotice(new NoticeEventArgs(NoticeType.Register, key, limitError, limitError.Message));
149 | // if (isThrow) throw error;
150 | // return this;
151 | //}
152 | var added = _dic.TryAdd(key, new ItemInfo
153 | {
154 | ib = this,
155 | key = key,
156 | create = create,
157 | idle = idle.Value,
158 | });
159 | if (added == false)
160 | {
161 | this.OnNotice(new NoticeEventArgs(NoticeType.Register, key, error, error.Message));
162 | if (isThrow) throw error;
163 | return false;
164 | }
165 | this.OnNotice(new NoticeEventArgs(NoticeType.Register, key, null, $"{key} 注册成功,{_usageQuantity}/{Quantity}"));
166 | return true;
167 | }
168 | bool InternalRemove(TKey key, bool isNow, bool isThrow)
169 | {
170 | if (IsDisposed)
171 | {
172 | if (isThrow) throw new Exception($"{key} 删除失败 ,{nameof(IdleBus)} 对象已释放");
173 | return false;
174 | }
175 | if (_dic.TryRemove(key, out var item) == false)
176 | {
177 | var error = new Exception($"{key} 删除失败 ,因为没有注册");
178 | this.OnNotice(new NoticeEventArgs(NoticeType.Remove, key, error, error.Message));
179 | if (isThrow) throw error;
180 | return false;
181 | }
182 |
183 | Interlocked.Exchange(ref item.releaseErrorCounter, 0);
184 | if (isNow)
185 | {
186 | item.Release(() => true);
187 | this.OnNotice(new NoticeEventArgs(NoticeType.Remove, item.key, null, $"{key} 删除成功,{_usageQuantity}/{Quantity}"));
188 | return true;
189 | }
190 |
191 | item.lastActiveTime = DateTime.Now;
192 | if (item.value == null) item.lastActiveTime = DateTime.Now.Subtract(item.idle).AddSeconds(-60); //延时删除
193 | _removePending.TryAdd(Guid.NewGuid().ToString(), item);
194 | this.OnNotice(new NoticeEventArgs(NoticeType.Remove, item.key, null, $"{key} 删除成功,并且已标记为延时释放,{_usageQuantity}/{Quantity}"));
195 | return true;
196 | }
197 | void InternalRemoveDelayHandler()
198 | {
199 | //处理延时删除
200 | var removeKeys = _removePending.Keys;
201 | foreach (var removeKey in removeKeys)
202 | {
203 | if (_removePending.TryGetValue(removeKey, out var removeItem) == false) continue;
204 | if (DateTime.Now.Subtract(removeItem.lastActiveTime) <= removeItem.idle) continue;
205 | try
206 | {
207 | removeItem.Release(() => true);
208 | }
209 | catch (Exception ex)
210 | {
211 | var tmp1 = Interlocked.Increment(ref removeItem.releaseErrorCounter);
212 | this.OnNotice(new NoticeEventArgs(NoticeType.Remove, removeItem.key, ex, $"{removeKey} ---延时释放执行出错({tmp1}次):{ex.Message}"));
213 | if (tmp1 < 3)
214 | continue;
215 | }
216 | removeItem.Dispose();
217 | _removePending.TryRemove(removeKey, out var oldItem);
218 | }
219 | }
220 |
221 | void OnNotice(NoticeEventArgs e)
222 | {
223 | this.Notice?.Invoke(this, e);
224 | }
225 |
226 | #region Dispose
227 | ~IdleBus() => Dispose();
228 | public bool IsDisposed { get; private set; }
229 | object isdisposedLock = new object();
230 | public void Dispose()
231 | {
232 | if (IsDisposed) return;
233 | lock (isdisposedLock)
234 | {
235 | if (IsDisposed) return;
236 | IsDisposed = true;
237 | }
238 | foreach (var item in _removePending.Values) item.Dispose();
239 | foreach (var item in _dic.Values) item.Dispose();
240 |
241 | _removePending.Clear();
242 | _dic.Clear();
243 | _usageQuantity = 0;
244 | }
245 | #endregion
246 | }
247 |
--------------------------------------------------------------------------------