Rakesh
Rakesh

Reputation: 2790

Using semaphore in C#

Hi I am trying to use Semaphore in my application. I have declared like this.

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();
    }
}

But I am not able to compile It's giving me this error:

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

But I have already added the namespace using System.Threading; I am able to using Mutex. May be what was I am missing. There is any other reference need to add.? I am using VS 2010. Framework 4.0

Upvotes: 3

Views: 2412

Answers (4)

oleksii
oleksii

Reputation: 35895

This code compiles for me

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
  • Single reference to System.dll v4.0.0.0, Runtime version v4.0.30319, Located at C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\System.dll

Upvotes: 0

Rukun Zaman
Rukun Zaman

Reputation: 61

It is better if you add 4.0 version to get the appropriate reference for Semaphore class.

Upvotes: 1

user195488
user195488

Reputation:

Semaphores were introduced in .NET 2.0

System.Threading.dll was added in .NET 4.0 (though the namespace System.Threading has been around since v1). Maybe your project includes an older version of System.Threading.

It is a frequently asked question The type or namespace '' does not exist in the class or namespace '' (are you missing an assembly reference?)

You need to add a reference in your project to an assembly where that namespace is defined or you are missing an using statement despite you stating that you are using System.Threading.

Upvotes: 1

vborutenko
vborutenko

Reputation: 4443

 .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

May you need another version of framework

Upvotes: 1

Related Questions