开发者

How to thread/which thread to use for background DLing .NET

开发者 https://www.devze.com 2022-12-10 08:10 出处:网络
I am writing front end app that conne开发者_如何学JAVActs 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

I am writing front end app that conne开发者_如何学JAVActs 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?


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";
        });
    };


There is only 1 kind of Thread, but a variety of ways to use them. Since you are working from a GUI (WinForms?) the BackgroundWorker is most suitable.

You could use async or sync I/O from there.

You should not Abort() a Thread, but Close or Cancel your connection. Depnds on wht you want to use.


You should probably look into ThreadPool.QueueUserWorkItem


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

0

精彩评论

暂无评论...
验证码 换一张
取 消