How to use multiple threads of the same class in C #

I have a class with a bunch of methods in. for instance

private int forFunction(String exceptionFileList, FileInfo z, String compltetedFileList, String sourceDir) { atPDFNumber++; exceptionFileList = ""; int blankImage = 1; int pagesMissing = 0; //delete the images currently in the folder deleteCreatedImages(); //Get the amount of pages in the pdf int numberPDFPage = numberOfPagesPDF(z.FullName); //Convert the pdf to images on the users pc convertToImage(z.FullName); //Check the images for blank pages blankImage = testPixels(@"C:\temp", z.FullName); //Check if the conversion couldnt convert a page because of an error pagesMissing = numberPDFPage - numberOfFiles; } 

Now what I'm trying to do now is access this class in a thread .. but not only one thread, maybe about 5 threads to speed up processing, since one of them is a bit slow.

Now, in my opinion, this will be chaos ... I mean one thread that changes variables, while another thread is busy with them, etc. etc. and blocks every variable in all of these methods ... not going to have a good time ...

So I suggest and don’t know if this is right ... this

  public void MyProc() { if (this method is open, 4 other threads must wait) { mymethod(var,var); } if (this method is open, 4 other threads must wait and done with first method) { mymethod2(); } if (this method is open, 4 other threads must wait and done with first and second method) { mymethod3(); } if (this method is open, 4 other threads must wait and done with first and second and third method) { mymethod4(); } } 

Would this be the right way to approach the problem of multiple threads accessing multiple methods at the same time?

These threads will have access only to the class 5 times, and no more, since the workload will be divided equally.

+4
source share
1 answer

Yes, this is one of your options. However, the conditional expression needs to be replaced using the lock statement, or even better, to synchronize this method:

 [MethodImpl(MethodImplOptions.Synchronized)] private int forFunction(String exceptionFileList, FileInfo z, String compltetedFileList, String sourceDir) 

This is not conditional, because there is nothing conditional. The next upcoming thread should wait, and then it should continue. He literally sleeps without following any instructions, and then woke up outside.

Note also that when you are concerned about confused variables during parallel execution of an unsynchronized method, this applies only to member variables (class fields). It does not apply to local variables declared inside the method, since each thread has its own copy.

+5
source

Source: https://habr.com/ru/post/1438354/


All Articles