Sometimes, however, there are long-running operations which need to be allowed to run without freezing the UI.
The QueueUserWorkItem method is a convenient way to execute a method while the .NET framework manages the threading. The traditional challenge has been the method signature for the function that is passed — it takes one parameter of type object (you can create a type, modify the signature, etc., but it has always seemed unnatural modifying signatures to accommodate the threading apparatus.)
Dynamic types are an alternative approach
Suppose you have code like that found below.
private void ProcessQueue(string jobId, string vaultName, string outputPath) { // ... }
One way to make it work with the WaitCallback signature is to create an overload that accepts a dynamic parameter (shown below)
public void ProcessQueue(dynamic obj) { this.ProcessQueue(obj.jobId, obj.vaultName, obj.outputPath); }
This overload calls the original method. The advantage to the approach is that it does not require the creation of a new type. The call can be made using an anonymous type as shown below.
System.Threading.ThreadPool.QueueUserWorkItem( this.ProcessQueue,
new { jobId = jobId, vaultName = vaultName, outputPath = "..." } );
new { jobId = jobId, vaultName = vaultName, outputPath = "..." } );
Quicker. More natural IMHO.
No comments:
Post a Comment