views:

96

answers:

3

I am writing front end app that connects to a DB and downloads any package it needs for a specified project. The user should be able to close the app which will not start any more DLs and wait for the current to finish and an option to forcefully close which will disconnect the current download and quit.

The files i am downloading may be on several server that are not my own. What kind of threads should i use? IIRC there were more then one type on .NET. What commands can i use to tell them to close now (this may be different then terminate) in case the user request to shut down right away?

A: 

You should probably look into ThreadPool.QueueUserWorkItem

James L
A: 

Look at the BackgroundWorker componet if you are using .NET 2 or newer.

Kane
+3  A: 

In the scenario given, you should be able to use the async nature of things like HttpWebRequest / WebClient, which will support all this already, using completion-ports rather than just threads.

Re "kill now" - you should never abort a thread unless you are tearing down your process. This is a bad thing, and can leave the system in a corrupt state, or with irretrievable locks. However tool itself may offer alternatives:

    WebClient wc = new WebClient();
    wc.DownloadFileCompleted += (sender, args) =>
    {
        if (args.Cancelled) Console.WriteLine("cancelled");
        else if (args.Error != null) Console.WriteLine(args.Error.Message);
        else Console.WriteLine("got it");
    };
    wc.DownloadFileAsync(uri, filePath);
    // wc.CancelAsync(); // to abort

Note that in an async callback (the DownloadFileCompleted above) you would, in anything like winforms/wpf, have to switch to the UI thread; for example:

    wc.DownloadFileCompleted += (sender, args) =>
    {
        this.Invoke((MethodInvoker) delegate {
            if (args.Cancelled) txtStatus.Text = "cancelled";
            else if (args.Error != null) txtStatus.Text = args.Error.Message;
            else txtStatus.Text = "got it";
        });
    };
Marc Gravell