Vydělávej až 160.000 Kč měsíčně! Akreditované rekvalifikační kurzy s garancí práce od 0 Kč. Více informací.
Hledáme nové posily do ITnetwork týmu. Podívej se na volné pozice a přidej se do nejagilnější firmy na trhu - Více informací.
Avatar
Duplicate
Člen
Avatar
Duplicate:24.3.2019 11:16

Ahoj,

Měl bych takový zajímavý problém:

Mám vytvořený custom-made form ve vlastní třídě pro udržení organizace v kodu nějak takto:

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace Ultra_Script.MessageBoxes
{
    public class MsgBoxes
    {
        #region MsgBox k výběru základního SW (stažení z netu nebo Synology)
        public static void SynoInternet()
        {
            Application.EnableVisualStyles();
            Form SynoInternet = new Form();

            Button Synology = new Button()
            {
                Left = 80,
                Width = 90,
                Height = 30,
                Top = 75,
                Text = "Synology"
            };

            Button Internet = new Button()
            {
                Left = 190,
                Width = 90,
                Height = 30,
                Top = 75,
                Text = "Internet"
            };

            Label SynoInternetLabel = new Label()
            {
                Left = 60,
                Width = 350,
                Height = 25,
                Top = 30,
                Text = "Chceš SW stáhnout z internetu nebo HD Synology?"
            };

            Label fasterLabel = new Label()
            {
                Left = 80,
                Width = 60,
                Height = 20,
                Top = 110,
                Text = "(Rychlejší)"
            };

            SynoInternet.Width = 380;
            SynoInternet.Height = 170;
            SynoInternet.Controls.Add(fasterLabel);
            SynoInternet.Controls.Add(SynoInternetLabel);
            SynoInternet.Controls.Add(Synology);
            SynoInternet.Controls.Add(Internet);

            Synology.Click += (sender, args) =>
            {
                SynoInternet.Dispose();
                Installation_Functions.InstallBasicSW();
            };

            Internet.Click += (sender, args) =>
            {
                MessageBox.Show("You clicked Internet");
            };

            SynoInternet.ShowDialog();

        }
        #endregion

    }
}

Jde mi v podstatě o tuhle část:

Synology.Click += (sender, args) =>
           {
               SynoInternet.Dispose();
               Installation_Functions.InstallBasicSW();
           };

Zavolá to funkci, která začne z internetu stahovat soubory, což se sice spustít ale zastaví se to na timetou té funkce. Funkce vypadá nějak takhle:

Zavolání funkce například:

FileDownloader.DownloadFile("https://github.com/Corbieman/Basic_SW/raw/master/JaVa.exe", @"C:\Windows\Temp\JaVa.exe", 9999);

A samotná funkce pro stahování vypadá takto:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Threading;

namespace Ultra_Script
{
    class FileDownloader
    {

        private readonly string _url;
        private readonly string _fullPathWheretoSave;
        private bool _result = false;
        private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0);

        public FileDownloader(string url, string fullPathWheretoSave)
        {

            if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url");
            if (string.IsNullOrEmpty(fullPathWheretoSave)) throw new ArgumentNullException("fullPathWhereToSave");

            this._url = url;
            this._fullPathWheretoSave = fullPathWheretoSave;

        }

        public bool StartDownload(int timeout)
        {

            try
            {
                System.IO.Directory.CreateDirectory(Path.GetDirectoryName(_fullPathWheretoSave));

                if (File.Exists(_fullPathWheretoSave))
                {
                    File.Delete(_fullPathWheretoSave);
                }
                using (WebClient client = new WebClient())
                {
                    var ur = new Uri(_url);
                    //client.Credentials = new NetworkCredential("username", "password");
                    client.DownloadProgressChanged += WebClientDownloadProgressChanged;
                    client.DownloadFileCompleted += WebClientDownloadCompleted;
                    Console.WriteLine(@"Stahuji potrebne soubory:");
                    client.DownloadFileAsync(ur, _fullPathWheretoSave);
                    _semaphore.Wait(timeout);
                    return _result && File.Exists(_fullPathWheretoSave);
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Cant download file");
                Console.Write(e);
                return false;
            }
            finally
            {
                this._semaphore.Dispose();
            }

        }

        private void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Console.Write($"/r --> {e.ProgressPercentage}%");
        }

        private void WebClientDownloadCompleted(object sender, AsyncCompletedEventArgs args)
        {
            _result = !args.Cancelled;
            if (!_result)
            {
                Console.Write(args.Error.ToString());
            }
            Console.WriteLine(Environment.NewLine + "Download Finished!");
            _semaphore.Release();
        }

        public static bool DownloadFile(string url, string fullPathWhereToSave, int timeoutInMilliSec)
        {
            return new FileDownloader(url, fullPathWhereToSave).StartDownload(timeoutInMilliSec);
        }

    }

}

Když tu funkci spustím z konzole vše funguje jak má, ale jakmile jí zavolám přes to tlačítko na formu, tak dostanu jenom "Stahuju potrebne soubory", běží do konce timeout a pak se to vypne.

Někdo by tušil kde by mohl být problém?

Díky za všechny rady,

Honza

Zkusil jsem: Smazat semaphore metodu - nepomohlo.

Chci docílit: Aplikace která sloužení k automatizování stahování a instalaci základního SW počítače.

 
Odpovědět
24.3.2019 11:16
Avatar
JerryM
Člen
Avatar
JerryM:25.3.2019 17:32

A napadlo tě nedělat to lambda výrazem a otestovat normálně delegate ???
ten totiž v debug režimu lépe otestuješ ...

 
Nahoru Odpovědět
25.3.2019 17:32
Děláme co je v našich silách, aby byly zdejší diskuze co nejkvalitnější. Proto do nich také mohou přispívat pouze registrovaní členové. Pro zapojení do diskuze se přihlas. Pokud ještě nemáš účet, zaregistruj se, je to zdarma.

Zobrazeno 2 zpráv z 2.