Mold Freeze Prevention

I would like to upload a picture and then show it in the picture.

I liked this at first:

WebClient client = new WebClient();
client.DownloadFile(url, localFile);
pictureBox2.Picture = localFile;

But that was not the case, because at the time the download was in progress, the application freezes.

Then I changed to this:

public class ParamForDownload
{
    public string Url { get; set; }
    public string LocalFile { get; set; }
}
ParamForDownload param = new ParamForDownload()
        {
            Url = url,
            LocalFile = localFile
        };

      ThreadStart starter = delegate { DownloadMap (param); };
        new Thread(starter).Start();

        pictureBox2.Picture = localFile;



    private static void DownloadMap(ParamForDownload p) 
    {
        WebClient client = new WebClient();
       client.DownloadFile(p.Url, p.LocalFile);
    }

But now I have to do something like "wait for thread end", because the file is accessed in the stream and at the same time I downloaded something to the file using the DownloadMap method.

What is the best way to wait to solve this problem?

+3
source share
4 answers

, , , , ( ). , , , ( ) . :

, .

, . DoWork, .

RunWorkerCompleted, . (pictureBox2.Picture = localFile;).

, , , .

Thread. , Thread.Start(), " ":

private delegate void MyFunctionCaller();

private static void DownloadMap(ParamForDownload p) 
{
    WebClient client = new WebClient();
   client.DownloadFile(p.Url, p.LocalFile);
    DownloadMapComplete(p);
}

private void DownloadMapComplete(ParamForDownload p)
{
if (InvokeRequired == true)
  {
  MyFunctionCaller InvokeCall = delegate { DownloadMapComplete(p); };
  Invoke(InvokeCall);
  }
else
  {
  pictureBox2.Picture = p.LocalFile;
  }
}
+13

Picturebox.LoadAsync() Picturebox . , LoadCompleted ( ).

:

pictureBox1.LoadAsync(@"http://imgs.xkcd.com/comics/tech_support_cheat_sheet.png");

- , .

+2

, :

1) , , - . IE: " , , ...". - (, , WebClient .., , ).

2) WebClient 'DownloadFileCompleted'.

3) WebClient DownloadFileAsync, . .

4) "DownloadFileCompleted" , . .

: http://weblogs.asp.net/justin_rogers/pages/126345.aspx

and: http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx

5) After the event has been redirected back to the user interface stream, open the file and update the user interface as necessary (IE: Re-enable fields, etc.).

Leather.

+1
source

Not related to the problem of streaming, but if you have no other requirements for saving photos to disk, you can do this:

WebClient client = new WebClient();
byte[] data = client.DownloadData(item.Url);
MemoryStream ms = new MemoryStream(data);
Bitmap img = new Bitmap(ms);
pictureBox.Image = img;
+1
source

Source: https://habr.com/ru/post/1715893/


All Articles