【问题标题】:Call same method from different threads从不同的线程调用相同的方法
【发布时间】:2011-11-24 02:31:24
【问题描述】:

例如,我们有 5 个正在运行的线程。他们每个人都调用相同的方法。当方法被调用时,它会在当前线程上运行吗?那意味着同一个方法会在(相对)同一时间在不同线程上分别运行?

例子:

public string GetHhmlCode(string url)
{
// ... Some code here
return html;
}

如果我们同时从不同的线程以不同的参数调用该方法,结果将返回到相应的线程,这是否意味着代码在不同的线程上单独运行?

【问题讨论】:

标签: c# multithreading methods call


【解决方案1】:

第一个问题的简短回答是:是的!该方法将由多个线程同时执行。

第二个问题的答案是:是的(有保留)!如果您从给定的线程上下文进入,则该方法将返回到相同的线程上下文,并且所有线程通常会表现得好像另一个线程不存在一样。但是,如果线程必须在同一个变量上读取和/或写入,这将很快改变。考虑这种情况:

class HttpClient
{
    private volatile bool _httpClientConnected;
    //.. initialize in constructor

    public string GetHtmlCode(string url)
    {
        string html = string.Empty;
        if(_httpClientConnected)
        {
            html = FetchPage(url);
        }
        return html;
    }

    public void Connect()
    {
        _httpClientConnected = true;
        ConnectClient();
    }

    public void Disconnect()
    {
        _httpClientConnected = false;
        DisconnectClient();
    }
}

假设需要连接客户端才能成功获取页面,那么考虑这个执行顺序:

Thread 1: calls GetHtmlCode
Thread 1: initialize local html variable
Thread 3: calls Disconnect()
Therad 2: calls GetHtmlCode
Thread 2: initialize local html variable
Thread 1: evaluate _httpClientConnected flag
Thread 3: sets _httpClientConnected to false
Therad 3: calls DisconnectClient() and successfully disconnects
THread 3: exits the Disconnect() method.
Thread 1: calls FetchPage()
Therad 2: evaluates _httpClientConnected flag
Thread 2: returns empty html string
Therad 1: catches an exception because it attempted to fetch a page when the client was disconnected

线程 2 正确退出,但线程 1 可能抛出异常,这可能会导致代码中出现其他问题。请注意,对标志本身的读/写将是安全的(即,由于标志被标记为易失性,这些操作是原子的并且对所有线程可见),但是存在竞争条件,因为可以在线程已经设置标志之后评估它。在这种情况下,有几种方法可以防止该问题:

  1. 使用同步块(类似于lock(syncObject){...})
  2. 为每个线程创建一个单独的 http 客户端(可能更高效并且避免同步)。

现在让我们看另一个例子:

public string GetHtmlCode(string url)
{
    string html = string.Empty;
    string schema = GetSchema(url);
    if(schema.Equals("http://"))
    {
        // get the html code
    }
    return html;
}

假设发生以下情况:

Thread 1: calls GetHtmlCode("http://www.abc.com/");
Thread 1: html is assigned an empty string
Thread 2: calls GetHtmlCode("ftp://www.xyz.com/");
Thread 2: html is assigned an empty string
Therad 1: assigns it's schema to the schema variable
Thread 2: assigns it's schema to the schema varaible
Thread 2: evaluates schema.Equals("http://")
Thread 1: evaluates schema.Equals("http://")
Thread 1: fetches html code
Therad 2: returns html
Therad 1: returns html

在这种情况下,两个线程都以不同的参数进入方法,只有线程 1 输入了一个可以允许它获取页面的参数,但线程 2 并没有干扰线程 1。发生这种情况的原因是线程不共享任何公共变量。传入url 参数的单独实例,并且每个线程还获得自己的本地模式实例(即模式不共享,因为它只存在于调用线程的上下文中)。

【讨论】:

  • 是的 - 我当然会为每个线程使用单独的 http 客户端。
  • 如果你引入了竞争条件,并且必须实现 lock() 机制,我一直想知道这是否意味着所有线程都必须等到另一个线程完成才能继续?如果是这样,如果您必须等待,那是否会破坏并发线程的目的?我总是发现它更容易,特别是如果我必须将参数传递给方法,只需将执行代码复制/粘贴到我线程的 DoWork() 方法中。这样,它们都真正同时运行并实现了效率。是吗?
【解决方案2】:

将此方法标记为静态,并且不要在此方法中引用外部变量。那么它会正常工作。

【讨论】:

  • 虽然这些通常是好主意,但对于线程安全来说既不是必要的也不是充分的。
猜你喜欢
  • 1970-01-01
  • 2014-12-12
  • 2013-08-30
  • 1970-01-01
  • 2013-11-09
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多