Elahe
Elahe

Reputation: 1399

C#: Share local variable in 2 different threads

Look at this sample code :

private void StartProgram()
{
    for (int i = 0; i < 10; i++)
    {
        if (true) // some conditions
        {
            int Temp = i; // every thread has different memory location for Temp variable.
            Thread ConnectThread = new Thread(ThreadMethod);
            ConnectThread.Start(Temp);
         }
    }
}

private static void ThreadMethod(object Index)
{
    int ID = (int)Index;
    int Result = 0;
    bool IsConnected;


    Result = ClientSMPP[ID].tcpConnect(Host[ID], int.Parse(Port[ID]));

    InsertToDatabaseMethod();
}

As I know, Temp variable has different location in memory for each thread. I mean every thread has a separate field for that. but when I want to do some actions in ThreadMethod, the ID field will conflict. I mean it doesn't have unique value in each time that ThreadMethod runs (for example ID's value is '1' 3 times). I know maybe more than 1 thread be in ThreadMethod, but they have different memory. I don't want to use Lock().

How Can I ignore this conflict?

Upvotes: 0

Views: 66

Answers (2)

JFish222
JFish222

Reputation: 1026

Per your request, moving this response to an "answer". Glad I could help! :)

You're calling InsertToDatabaseMethod() without passing a value.

If the value being inserted is coming from an external source (Ex: a property), then yes, a lock is the way to go.

If the value is local (ex: your inserting "ID" into the database, then you can pass the value as a parameter to avoid the lock: InsertToDatabaseMethod(ID)

Upvotes: 2

Steve Wellens
Steve Wellens

Reputation: 20620

You could simplify it like this:

  for (int i = 0; i < 10; i++)
    {
        if (true) // some conditions
        {                 
            Thread ConnectThread = new Thread(ThreadMethod);
            ConnectThread.Start(i);
        }
    }

Note that each thread has it's own stack. Local variables are stored on the stack.

You have no issue because ints are value types.

Upvotes: 0

Related Questions