Reputation: 3766
i have the following code, but the problem is that when i exucte it without using the delegate thread it goes smooth but when i use the delegate then it give me the erro:
NullReferenceException Was Unhandled, Object Reference not set to an instance of an object/
the code is:
public static string makezip_thread(string [] files,bool IsOriginal)
{
string paths="";
Thread starter = new Thread (delegate(){ paths = Makezipfile(files,IsOriginal);});
starter.IsBackground = true;
starter.Start();
return paths;
}
my zip Making Class:
public static string Makezipfile(string[] files, bool IsOriginal)
{
string[] filenames = new string[files.Length];
if (IsOriginal)
for (int i = 0; i < files.Length; i++)
filenames[i] = HttpContext.Current.Request.PhysicalApplicationPath + files[i].Remove(0,10).ToString();
else
for (int i = 0; i < files.Length; i++)
filenames[i] = HttpContext.Current.Request.PhysicalApplicationPath + files[i].Replace(HttpContext.Current.Request.UrlReferrer.ToString(), "");
string DirectoryName = filenames[0].Remove( filenames[0].LastIndexOf('/') );
DirectoryName = DirectoryName.Substring(DirectoryName.LastIndexOf('/') + 1).Replace("\\","");
try
{
string newFile = HttpContext.Current.Request.PhysicalApplicationPath + "images\\Thumbnails\\zipFiles\\" + DirectoryName + ".zip";
if(File.Exists(newFile))
File.Delete(newFile);
using (ZipFile zip = new ZipFile())
{
foreach (string file in filenames)
{
string newfileName = file.Replace("\\'", "'");
zip.CompressionLevel=0;
zip.AddFile(newfileName, "");
}
zip.Save(newFile);
}
return a;
}
Upvotes: 0
Views: 332
Reputation: 564771
This is not going to do exactly what you want, in any case.
By trying to push this into a separate thread, chances are you'll (probably always) return string.Empty
as a result of this method.
The reason for this is that your return paths;
line will return far before Makezipfile
can execute successfully.
If you want this to be an asynchronous method, you need to rework it to be an asynchronous method. There are many options, including the APM and the EAP models for asynchrony in .NET 3.5 and earlier. In .NET 4, the best option here would be to turn this into a method that returns Task<string>
:
public static Task<string> MakeZipAsync(string [] files,bool IsOriginal)
{
return Task.Factory.StartNew( () =>
{
return Makezipfile(files, IsOriginal);
});
}
You'd then use this like:
var zipTask = MakeZipAsync(files, true);
// Do other work...
// Later, when you need the results, you can block and retrieve them:
var paths = zipTask.Result;
Upvotes: 3