Rua*_*uan 4 c# methods multithreading class
我有一个包含大量方法的类.例如
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;
}
Run Code Online (Sandbox Code Playgroud)
现在我正在尝试的是在一个线程中访问该类..但不只是一个线程,可能是大约5个线程来加速处理,因为一个有点慢.
现在在我的脑海里,那将是混乱...我的意思是一个线程改变变量而另一个线程忙于他们等等,并锁定所有这些方法中的每个变量...不会有一个好的时间...
那么我提议,并且不知道它是否正确的方式......就是这样
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();
}
}
Run Code Online (Sandbox Code Playgroud)
这是解决多线程同时访问多个方法的问题的正确方法吗?
这些线程只能访问Class 5次,而不会更多,因为工作负载将平均分配.
是的,这是你的选择之一.但是,您应该使用该lock语句替换条件表达式,或者更好的是,使方法同步:
[MethodImpl(MethodImplOptions.Synchronized)]
private int forFunction(String exceptionFileList, FileInfo z, String compltetedFileList, String sourceDir)
Run Code Online (Sandbox Code Playgroud)
这不是一个有条件的因为这里没有任何条件.下一个即将到来的线程必须等待,然后必须继续.它实际上是在没有执行任何指令的情况下睡觉,然后从外面唤醒它.
另请注意,当您担心在非同步方法的并行执行期间混乱的变量时,这仅适用于成员变量(类字段).它不适用于在方法内声明的局部变量,因为每个线程都有自己的副本.
| 归档时间: |
|
| 查看次数: |
1662 次 |
| 最近记录: |