C# Multithreading -


OK I have to run two threads existing code:

  public void foo () { Lock (this) {while (stopThreads == incorrect) {foreach (var acc in myList) {// process some stuff}}}} public void bar () {lock (this) {while (stopThreads == false) {foreach (Var acc) in myList {// Process some stuff}}}}  

The same list, the problem is that the first thread is not issuing "foo" lock is; Because "bar" only starts when "foo" is done. Thanks

Yes, how this lock is designed to work.

Lock keyword can be found as a key block for a reported object by receiving interactive exclusion lock, executing a statement, and then issuing a lock as a key block .

Mutual-exclusion means that at any point of time, most of the threads that hold the lock can be.

Locking it on is a bad idea and frustrated. Instead you should make a personal object and lock it on it. To solve your problem, you can lock on two separate items.

  Private object lockObject1 = new object (); Private object lockObject2 = new object (); Public void foo () {lockObject1} {// ...}} Public Zero Times (lock) {lockObject2} {// ...}}  

Alternatively You can reuse the same lock, but take it inside the loop so that each loop gets an opportunity to move forward:

  while (stopThreads == incorrect) {foreach (var acc in myList) {Lock (lockObject) {// Process of some things}}}  

However, I suggest that you want to spend some time understanding it as long as it works on your machine No Lines of literacy to the code of what is happening rather than to re-order. It is difficult to write the correct multilingual code.

I will recommend this article to stop a thread:


Comments