如何在c#中实现这种多线程场景

时间:2015-08-06 01:38:41

标签: c# multithreading

我想做这样的事情:

function void DoSomething(string path){
    try {
        DownloadDataFromWebSite(path)
    }catch(OtherUserLoggedInUsingSameAcountException ex){         
         If (I am the first thread that get here){
              Login();
        }else{
             Wait for the first thread to finish Login();
        }        
        DownloadDataFromWebSite(path);   
    }        
}

我有一个我会称之为的集合:

 APathCollection.AsParallel().ForAll(DoSomething)

请帮帮我,我该如何实现这种模式?有可能吗?

PS:我已经省略了错误计数器,请假设它不会进入无限重复。

更新:我已更新代码以反映我在@IPValverde请求中的实际操作。

2 个答案:

答案 0 :(得分:1)

好的,您提供了有关您的方案的更多信息。我认为您可以创建第二个锁,指示您的某个线程是否正在登录。

这是一个片段:

var obj = {
  type: 'Unicorns',
  collects: ['stuff1', 'stuff2'],
  canFly: true
}

您可以在此处看到此示例:https://dotnetfiddle.net/SOXxO9

答案 1 :(得分:0)

当你谈论线程安全时,重要的是资源。

首先read about lock,特别是涉及关键部分的部分。

然后,在FixparticularException方法中为每个“逻辑”资源创建一个锁,你应该没问题。如果你提供一些细节,我可以更明确地为你编写代码,这里的重点是要点:

private bool _IsFixed;

public void DoSomething(int x)
{
    try 
    {
        DoWork(x)
    }
    catch (ParticularException pex)
    {
          FixParticularException(pex);
    }        
    DoSomething(x);   
}        

private void FixParticularException (ParticularException pex)
{
    lock (_resource1Lock)
    {
         if (_IsFixed)
             return;

        // fix it

        _IsFixed = true;
    }
}