C# 如何在C中使用同一类的多个线程#
我有一个类,里面有很多方法。比如说C# 如何在C中使用同一类的多个线程#,c#,multithreading,class,methods,C#,Multithreading,Class,Methods,我有一个类,里面有很多方法。比如说 private int forFunction(String exceptionFileList, FileInfo z, String compltetedFileList, String sourceDir) { atPDFNumber++; exceptionFileList = ""; int blankImage = 1; int
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;
}
现在我尝试的是在线程中访问该类。。但不只是一个线程,可能需要大约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();
}
}
这是解决多线程同时访问多个方法问题的正确方法吗
这些线程将只访问该类5次,不会更多,因为工作量将被平均分配。是的,这是您的选项之一。但是,应该使用
lock
语句替换已有的条件表达式,或者更好地使方法同步:
[MethodImpl(MethodImplOptions.Synchronized)]
private int forFunction(String exceptionFileList, FileInfo z, String compltetedFileList, String sourceDir)
这不是一个真正的条件,因为这里没有条件。下一个线程必须等待,然后才能继续。它实际上是在不执行任何指令的情况下睡觉,然后从外面被唤醒
还要注意,当您担心在非同步方法的并行执行过程中变量弄乱时,这只适用于成员变量(类字段)。它不适用于方法中声明的局部变量,因为每个线程都有自己的局部变量副本。术语的混合确实没有帮助。您不运行类,调用方法
myClass
也不常见。如果你能给出一个更具体的例子,这会有所帮助……如果你针对的是一种特定的语言,请在你的问题中加上这个标签。现在我添加了“java”标记,因为代码看起来像java。啊,该死的,我完全忘记了!感谢you@Ruan我也是。因为你的标签是c#,但答案中的示例是java(尽管差别很小)。@Ruan-谢谢分享,我已经手动应用了你的编辑。我想我最初在这里看到了一个Java错误标记。@Jirka-没问题。我想是的,Joachim补充道,他认为这是java,因为我一开始没有指定c。谢谢你,吉尔卡。