Dim
Dim

Reputation: 122

Read string from multiple threads

I need to set a value for a string just once: example

string ItemID= "1";

And then to use this string from multiple threads, for creating a query in sql server. Example:

Thread 1

SqlCommand cmd = new SqlCommand("Select * from inventory where itemid='"+ ItemID +"'");

Thread 2

SqlCommand cmd = new SqlCommand("Select * from inventory where itemid='"+ ItemID +"'");

and so on...

Is this method right? Reading a string from multiple threads is it safe? Is there any other way for what i want to achieve?

Upvotes: 0

Views: 367

Answers (1)

Alireza Yadegari
Alireza Yadegari

Reputation: 305

if I understand your question correctly . you want a way to work with property in multi thread option 1:

 var lockObject = new object();
    private string _itemId;
    public string ItemId
    {
        get
        {
            
                return _itemId;
            
        }
        set
        {
            if (string.IsNullOrEmpty(_itemId))
            {
                lock (lockObject)
                {
                    if (string.IsNullOrEmpty(_itemId))
                    {
                        _itemId = value;
                    }
                }
            }
        }

    }

option 2 :

private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);

    private string _itemId;
    public string ItemId
    {
        get
        {
            return _itemId;
        }
        set
        {
            if (string.IsNullOrEmpty(_itemId))
            {
                _semaphore.Wait();
                if (string.IsNullOrEmpty(_itemId))
                {
                    _itemId = value;
                }
                _semaphore.Release();

            }

        }

Upvotes: 1

Related Questions