views:

72

answers:

2

Hi,

I have small web app that generate PDF files as a report. I'm trying to delete those generated PDF files after 10 sec that they are generated. What I want to do is to read a folder with PDF files every 10 sec, and delete all the PDF files inside that folder.

I read this post of Easy Background Tasks in ASP.NET. The following code is the VB version.

    Protected Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    AddTask("DoStuff", 10)
End Sub

Private Sub AddTask(ByVal name As String, ByVal seconds As Integer)
    OnCacheRemove = New CacheItemRemovedCallback(CacheItemRemoved)
    HttpRuntime.Cache.Insert(name, seconds, Nothing, DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, _
     OnCacheRemove)
End Sub

Public Sub CacheItemRemoved(ByVal k As String, ByVal v As Object, ByVal r As CacheItemRemovedReason)
    ' do stuff here if it matches our taskname, like WebRequest

    DeletePDFilesInFoler()

    ' re-add our task so it recurs
AddTask(k, Convert.ToInt32(v))

End Sub

But I got this error

Delegate 'System.Web.Caching.CacheItemRemovedCallback' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.

If this code works, where I should put it. Right, now I'm putting it in the master page. How to get this error out?

Thank you

+1  A: 

The error is in the error message, you're missing AddressOf. Try this:

OnCacheRemove = New CacheItemRemovedCallback(AddressOf CacheItemRemoved)
Sam
Sam, Thank You for this. No more error. But I'm taking richardtallent's advice.
Angkor Wat
+1  A: 

Rather than deleting them on a schedule, why not look for old PDFs and delete them each time a PDF is generated?

Pseudo-code:

/* Clean up old PDFs */
If Not StaticCleaningUpPDFsNow Then
   // No other reports generating simultaneously and trying to delete old PDFs
   StaticCleaningUpPDFsNow = True 
   For each f in (reportfolder\*.pdf)
      If f.DateCreated.AddSeconds(10) < Now Then f.Delete
   Next
   StaticCleaningUpPDFsNow = False
End If
/* Create PDF for the current report */
...

The overhead to look for files in a folder and delete a few is incredibly small, and doing this on demand is a much better use of resources, without the hacks around cache expirations (and the edge cases that can result).

richardtallent
I'm taking this advice. Thank you. I'd like it it's so simple.
Angkor Wat