简体   繁体   English

如何正确同步这些线程?

[英]How to properly synchronize these threads?

I'm trying to properly handle files in a web app. 我正在尝试正确处理Web应用程序中的文件。 When downloading a file I lock on an object: 下载文件时,我锁定了一个对象:

lock(lockObject)
{
   //Download file here.
}

so that if that same file is about to be deleted from another thread while in the middle of the download, the "delete" thread waits for the "download" thread to finish first: 因此,如果在下载过程中要从另一个线程中删除同一文件,则“删除”线程将等待“下载”线程首先完成:

lock(lockObject)
{
   //Delete file here.
}

This works, but presents another problem: two threads cannot download the file simultaneously. 这可行,但是存在另一个问题:两个线程无法同时下载文件。

How can I make it so that multiple threads can run the "download" code simultaneously but at the same time not allow any thread to run the "delete" code until the "download" threads are done? 我如何才能使多个线程可以同时运行“下载”代码,但是在完成“下载”线程之前,不允许任何线程同时运行“删除”代码?

I know the answer is somewhere in the Monitor class, but I'm not sure how to pull it off. 我知道答案在Monitor类中的某个位置,但是我不确定如何实现。

Possibly a ReaderWriterLockSlim would do what you need. ReaderWriterLockSlim可能会满足您的需求。 Basically, you treat the download threads as readers and the delete threads as writers. 基本上,您将下载线程视为读取器,将删除线程视为写入器。 You can have any number of readers, but any writer requires exclusive access. 您可以有任意数量的阅读器,但是任何作者都需要独占访问权限。 So if any file is being downloaded when the delete method calls EnterWriteLock , the delete thread will have to wait until all current downloads have finished. 因此,如果在删除方法调用EnterWriteLock时正在下载任何文件,则删除线程将必须等待直到所有当前下载完成为止。

ReaderWriterLockSlim theLock = new ReaderWriterLockSlim();

void Delete(filename)
{
    theLock.EnterWriteLock();
    try
    {
        // do delete stuff here
    }
    finally
    {
        theLock.ExitWriteLock();
    }
}

void Download(filename)
{
    theLock.EnterReadLock();
    try
    {
        // do delete stuff here
    }
    finally
    {
        theLock.ExitReadLock();
    }
}        

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM