Okay, I've read a number of other posts on StackOverflow regarding multi-threading, but I don't see one that answers my specific question.
I have an MVC 3 application开发者_JAVA技巧 that is processing about 5000 records from an XML document into a database. I want to have the view contain an AJAX console that monitors the progress of the transaction (how many successfully write, how many fail, potential duplicate flags, etc). Can I have one controller instance running the process that populates a session-level variable as progress is made and have another instance that just gets called by the AJAX console at 1 second intervals to grab the session variable values?
Is there a better way? Multi-threading is what I see a lot of people referring to, but I don't see any solutions I can directly apply. Suggestions?
Your suggestion is workable, but will require some thought. If you have multiple AJAX requests coming in, then IIS will handle those requests on multiple threads, so you are into multi-threading. This means you must make access to the session state thread-safe. So you will require something like this:
// put an instance of this class in the user's Session
class Progress
{
public object Locker { get; private set; }
public Progress()
{
Locker = new Object();
}
public int SuccessCount { get; set; }
public int FailureCount { get; set; }
public int DuplicateCount { get; set; }
}
// update the counts in the processing logic inside a lock
Progress progress = Session[ ... ];
lock( progress.Locker )
{
progress.SuccessCount = ...
progress.FailureCount = ...
progress.DuplicateCount = ...
}
// read the counts in the progress handler also inside a lock on the same object
Progress progress = Session[ ... ];
lock( progress.Locker )
{
retval.SuccessCount = progress.SuccessCount;
retval.FailureCount = progress.FailureCount;
retval.DuplicateCount = progress.DuplicateCount;
}
return retval;
You will also have to handle the case where the processing thread finishes and removes the session object at the same time as a progress request is being processed. Also, you may have to handle multiple processing threads ( and thus Progress
objects ) in one session.
There's a bit to think about, but it is do-able.
精彩评论