2017-12-28 14 views
-1

내 상황은 이것이다 :한 번에 하나의 스레드에 의해 실행됩니다

  • 난 단지 이미 멀티 스레딩에서 실행되는 코드의 일부에 액세스 할 수있는, 그래서 ' 쓰레드가 생성되지 않고 쓰레드가 생성되는 코드 부분에 접근 할 수 없다.
  • 상당히 복잡한 (여러 함수가 호출되고 거기에 DB 액세스가 포함됨) 코드 부분이 있는지 확인해야한다. 한 번에 하나의 스레드 만 독점적으로 실행

그래서 내 qu estion은 가능합니까? 그렇다면 가장 좋은 방법은 무엇일까요?

: 내가 작은 조사 노력을했다 여기에 묻고 끝이를 읽기 전에

// This method is executed by multiple threads at the same time 
protected override void OnProcessItem() 
{ 
    MyObject myObject = new MyObject(); 

    // Begin of the code that should be executed only once at a time 
    // by each thread 

    bool result = myObject.DoComplexStuff(); 

    if(result == true) 
    { 
     this.Logger.LogEvent("Write something to log"); 
     // ... Do more stuff 
    } 
    else 
    { 
     this.Logger.LogEvent("Write something else to log"); 
     // ... Do more stuff 
    } 

    // ... Do more stuff 

    // End of the code that should be executed only once at a time 
    // by each thread 
} 

일부 배경

: 여기

내가 acomplish 노력하고있어 일부 설명 코드

https://docs.microsoft.com/en-us/dotnet/standard/threading/overview-of-synchronization-primitives

하지만 여전히 가장 좋은 방법이 무엇인지 또는 mi 시나리오에서 구현하는 방법.

또한 나는 당신이 추측 할 수있는 것처럼 멀티 스레딩 전문가가 아닙니다.

+3

을하고있다 lock에 대한 몇 가지 의견을 추가 한 lock을 넣어하는 것입니다? 'lock (syncObject) {/ * 한 번에 하나의 스레드 * /}'? 귀하의 경우 그것은'lock (this.Logger) {...}' –

+0

중복 된 표시에 대해서는 다른 게시물의 답변이 완전히 적용되지만 질문하는 방식에 따라 어려움이 있습니다. 좀 더 일반적인 방법으로 이것을 찾고 있다면 그것을 찾으십시오. –

답변

1

예,이 경우 lock을 사용할 수 있습니다. 클래스에 비공개 동기화 개체를 만들고이 개체에 대한 잠금을 획득하면 한 번에 하나의 스레드 만 lock 블록 내의 코드를 실행할 수 있습니다.

class Foo 
{ 
    private readonly object syncObj = new object(); 

    public void Blah() 
    { 
      lock (syncObj) 
      { 
       //only one thread at a time 
       //will execute this code 
      } 
    } 
} 
+0

실제로 객체 잠금에 대해 읽었지만 동기화를위한 더미 객체를 만들지는 않았지만 잠금 접근 방식을 사용하기 위해서는 단일 객체를 잠글 필요가 있다고 생각했습니다. 고마워. –

+1

@ManuelNavarro 환영합니다! 하나의 작은 주석 : 위의 코드는 Foo *의 각 인스턴스에 대해 한 번에 하나의 스레드가 잠금 내부의 코드를 실행하도록합니다. 필요한 경우'Foo'의 어떤 인스턴스에 상관없이 코드가 하나의 쓰레드에 의해서만 실행될 수 있고'syncObj'를 정적으로 만들어야한다는 것입니다. – InBetween

2

가장 쉬운 방법은, 예컨대 :

// static: conservative policy: no two threads in the entire application 
// can enter locked block at the same time. 
// You may want to be more lenient and lock, say on this.Logger i.e. 
// no two theards addressing the same Logger... 
private static object syncObject = new object(); 

... 

protected override void OnProcessItem() { 
    MyObject myObject = new MyObject(); 

    // Begin of the code that should be executed only once at a time 
    lock (syncObject) { 
    bool result = myObject.DoComplexStuff(); 

    if (result) { 
     this.Logger.LogEvent("Write something to log"); 

     // ... Do more stuff 
    } 
    else { 
     this.Logger.LogEvent("Write something else to log"); 

     // ... Do more stuff 
    } 

    // ... Do more stuff 
    } 
    // End of the code that should be executed only once at a time by each thread 
} 
0

난 당신이 lock``을 찾고 계십니까 방법

private object _OnProcessItemLockObject = new object(); 
// This method is executed by multiple threads at the same time 
protected override void OnProcessItem() 
{ 
    MyObject myObject = new MyObject(); 

    // Begin of the code that should be executed only once at a time 
    // by each thread 

    bool result = false; 
    lock(_OnProcessItemLockObject) 
    { 
     //mat: the part inside the lock will only be executed by one thread. All other threads will wait till the lock-object is unlocked. 
     result = myObject.DoComplexStuff(); 
    } 

    //mat: the following code will get executed parallel 
    if(result == true) 
    { 
     this.Logger.LogEvent("Write something to log"); 
     // ... Do more stuff 
    } 
    else 
    { 
     this.Logger.LogEvent("Write something else to log"); 
     // ... Do more stuff 
    } 

    // ... Do more stuff 

    // End of the code that should be executed only once at a time 
    // by each thread 
}