使用线程本地存储进行此操作安全吗? [英] Is using thread local storage safe for this operation?

查看:58
本文介绍了使用线程本地存储进行此操作安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET Web应用程序,允许最终用户上传文件.一旦文件在服务器上,我就产生一个线程来处理文件.向线程传递有关特定操作( UserId ,文件路径,各种选项等)的数据.大多数数据是通过对象和方法参数传递的,但是 UserId 需要更全局地可用,因此我将其放在线程本地存储中.

I have a ASP.NET web application that allows end users to upload a file. Once the file is on the server, I spawn a thread to process the file. The thread is passed data regarding the specific operation (UserId, file path, various options, etc.). Most of the data is passed around via objects and method parameters but UserId needs to be available more globally so I put it in thread-local storage.

线程很长,但是它只处理文件并中止.在这种情况下,我对命名数据插槽的使用是否安全?如果UserA上传文件,然后UserB在仍在处理第一个文件的同时上传文件,是否可能还会委派UserA的线程来​​处理UserB,从而导致命名插槽发生冲突?(即,该插槽将被UserB的ID覆盖,而UserA的文件的其余操作都链接到错误的用户UserB).

The thread is lengthy but it just processes the file and aborts. Is my use of the named data slot safe in this circumstance? If UserA uploads a file then UserB uploads a file while the first file is still processing, is it possible that the thread for UserA will also be delegated to handle UserB, thus producing a conflict for the named slot? (i.e. The slot gets overwritten with UserB's id and the rest of the operation of UserA's file is linked to the wrong User, UserB).

Public Class FileUploadProcess
    Public UserId as String

    Public Sub ExecuteAsync()
        Dim t As New Thread(New ThreadStart(AddressOf ProcessFile))
        t.Start()
    End Sub

    Protected Sub ProcessFile()
        Dim slot As LocalDataStoreSlot = Thread.GetNamedDataSlot("UserId")
        Thread.SetData(slot, UserId)

        'lengthy operation to process file

        Thread.FreeNamedDataSlot("UserId")
        Thread.CurrentThread.Abort()
    End Sub
End Class

注意,我不是在问 LocalNamedDataStore 插槽是否是线程安全的.根据定义,我知道它们是.

Note that I am not asking if the LocalNamedDataStore slots are thread-safe. By definition, I know that they are.

推荐答案

在这种情况下,使用线程本地存储是安全的.没有两个线程将共享同一本地存储(因此它是本地线程).因此,两个并发请求不会占用其他数据.

In this case your use of thread local storage is safe. No two threads will ever share the same local storage (hence it's thread local). So there is no chance that two concurrent requests will stomp on the others data.

虽然还有其他评论

  • 请避免使用 Thread.Abort .这是非常危险的操作,实际上这里不需要.该线程将在此之后结束该语句.
  • 更好的方法是创建一个类,该类包含具有 UserId 作为本地字段的后台操作.每个请求都会获得一个新的类实例.这是一种将数据传递到后台任务的简便得多的方法
  • Do avoid the use of Thread.Abort. It's a very dangerous operation and truthfully not needed here. The thread will end the statement afterwards.
  • A better approach would be to create a class which contains the background operation that has the UserId as a local field. Each request gets a new class instance. This is a much easier way to pass the data around to the background tasks

这篇关于使用线程本地存储进行此操作安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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