Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 373
  • Last Modified:

Using Regex MatchEvaluators with an SqlConnection

Hi,

I wrote code that searches an XML document for patterns (using Regex) of the form #<variable-name>#, and then substitutes the right value for <variable-name> by querying an SQL database.

To do the substitutions, I'm using Regex.Replace() with a MatchEvaluator function.

My problem is, MatchEvaluator is a static function, so it can't access the class's existing non-static SqlConnection to query the database.  If I make the SqlConnection static, it becomes non-thread-safe.  For efficiency reasons, I don't want to open a new SqlConnection every time I call MatchEvaluator.  Is there any way to do this?
0
yizchaknaveh
Asked:
yizchaknaveh
2 Solutions
 
NipNFriar_TuckCommented:
Some possibilities are that you could do a type of singleton or you can make the connection static and then do a lock on the connection, lastly you could create a non static function that calls the static function and let the non static function get the connection and pass it in to the static function.

Hope this helps...
0
 
drichardsCommented:
MatchEvaluator does not have to be a static function.  If you have an instance of an object (obj) with a member function 'Func', you can do:

    MatchEvaluator me = new MatchEvaluator(obj.Func);

and Func will be called in the context of object 'obj'.

And according to the SqlConnection docs, "Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe."  Read at:

   http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemDataSqlClientSqlConnectionClassTopic.asp

It would seem that you want the SqlConnection to be static anyway.  Do you know of documentation to the contrary?
0
 
yizchaknavehAuthor Commented:
Excellent.  Thanks.  I made it non-static and all problems went away.  I'm not sure why I thought it had to be static.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now