0

I will try my best to describe what I need to know. I'm using C# (WPF .NET 4), multithreading by using a BlockingCollection. The threads contain infinite loops, so they are never going to die and they are going in turns (1st - 2nd - 1st - 2nd etc). While each thread is active it is showing in my GUI "Thread X is active".

Now, I have a couple of buttons on my GUI, but right now when I click randomButton it calls the same method from thread 1 and thread 2.

How can I make it so it calls only the method from the active thread? Is there a way to write something in my thread that basically says "If this thread is active the buttons will only affect this thread"?

A Petrov
  • 417
  • 1
  • 9
  • 23

1 Answers1

0

I think you have a misunderstanding of threading.

Lets define a Thread:

Thread

A thread is the entity within a process that can be scheduled for execution. All threads of a process share its virtual address space and system resources. In addition, each thread maintains exception handlers, a scheduling priority, thread local storage, a unique thread identifier, and a set of structures the system will use to save the thread context until it is scheduled. The thread context includes the thread's set of machine registers, the kernel stack, a thread environment block, and a user stack in the address space of the thread's process. Threads can also have their own security context, which can be used for impersonating clients.

When you run a method inside a Thread in your application, may it be a Background Thread or a Foreground Thread, you are executing a unit of work in parallel to the applications Main Thread, which in your case is the UI Thread of your GUI.

"How can I make it so it calls only the method from the active thread?"

When you start a Thread, it runs until it has finished execution (either by finishing work or terminating due to an exception or thread abortion). So when you start multiple threads simultaneously, invoking same method, they will all run it at the same time, since they are all active

You can use Concurrent Collections which let you access collections inside a multithreaded environment

I suggest you read more about processes and threads here and here

Community
  • 1
  • 1
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321