如何确保一部分代码一次只由一个线程运行 [英] How to ensure a portion of code is run by just one thread at a time

查看:76
本文介绍了如何确保一部分代码一次只由一个线程运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况是这样的:

  • 我只能访问已在多线程中运行的部分代码,因此我没有创建线程,也无法访问正在创建线程的代码部分
  • 我需要确保一段相当复杂的(调用多个函数,涉及数据库访问等)部分代码一次只由一个线程执行

所以我的问题是,有可能做到吗?如果是这样,最好的方法是什么?

So my question is, it is possible to do that? and if that so, what is the best way to do it?

以下是我尝试完成的一些说明性代码:

Here is some illustrative code of what I'm trying to acomplish:

// 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
}

一些背景

在问这里之前,我做了一个小调查工作并结束阅读:

Before asking here I did an small investigation effort and end reading this:

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

但我仍然不确定最好的方法是什么,或者如何在 mi 场景中实现它.

But still I'm not sure what's the best approach or how to implement it in mi scenario.

此外,正如您可能猜到的,我不是多线程方面的专家.

Additionally I'm no expert at multithreading as you may guess.

推荐答案

是的,您可以为此使用 lock.在你的类中创建一个私有的同步对象,获取这个对象的锁,一次只有一个线程能够执行 lock 块中的代码.

Yes, you can use lock for this. Create a private synchronization object in your class, acquire the lock on this object and only one thread at a time will be able to execute the code within the lock block.

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

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

这篇关于如何确保一部分代码一次只由一个线程运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆