在c#中使用信号量

本文关键字:信号量 | 更新日期: 2023-09-27 18:06:19

你好,我试图在我的应用程序中使用Semaphore。我是这样声明的。

class MyThread
{
    public Thread Thrd;
    static Semaphore sem = new Semaphore(2, 2);
    public MyThread(string name)
    {
        Thrd = new Thread(this.Run);
        Thrd.Name = name;
        Thrd.Start();
    }
}

但是我无法编译它给了我这个错误:

The type or namespace name 'Semaphore' could not be found 
(are you missing a using directive or an assembly reference?)

但是我已经添加了名称空间using System.Threading;,我能够使用互斥。也许是我错过了什么。还有什么参考资料需要补充的吗?我使用的是VS 2010。Framework 4.0

在c#中使用信号量

信号量是在。net 2.0中引入的

System. threading .dll是在。net 4.0中添加的(通过命名空间System. threading .dll)。线程从v1开始就存在了。也许你的项目包含一个旧版本的System.Threading.

类型或名称空间"在类或名称空间中不存在"(您是否缺少程序集引用?)

您需要在项目中向定义该名称空间的程序集添加引用,或者尽管您声明正在使用System.Threading.

,但您缺少using语句。
 .NET Framework
 Supported in: 4.5, 4, 3.5, 3.0, 2.0
.NET Framework Client Profile
 Supported in: 4, 3.5 SP1
 Portable Class Library
 Supported in: Portable Class Library
 .NET for Windows Store apps
 Supported in: Windows 8

可能你需要另一个版本的框架

最好添加4.0版本以获得适当的信号量类引用

这段代码为我编译

using System.Threading;
namespace ConsoleApp1
{
    class MyThread
    {
        static Semaphore sem = new Semaphore(2, 2);
    }
    class Program
    {
        static void Main(string[] args) { }
    }
}
    VS 2010
  • 。NET 4.0
  • System.dll v4.0.0.0,运行时版本v4.0.30319,位于C:'Program Files (x86)'Reference Assemblies'Microsoft'Framework.NETFramework'v4.0'System.dll