将图像加载到另一个线程上的PictureBox中

时间:2011-01-22 15:10:27

标签: winforms multithreading image c#-3.0 picturebox

我正在尝试根据(英国)邮政编码加载根据Google静态地图按需提取的图片。

假设我有一个客户,客户有一个地址。客户端的一个属性是PostCode。我有一个加载客户端的表单。我将客户端ID提供给此表单的构造函数,然后使用LINQ 2 SQL加载包括地址在内的各种信息。

private void LoadBranchDetails() {
  Text_Update_BI_Name.Text = Branch.BranchNumber;
  Text_Update_BI_Manager.Text = String.Format("{0} {1}", Branch.PharmacyManager.FirstName, Branch.PharmacyManager.LastName);
  DropDownList_Update_BI_Coordinator.SelectedValue = Branch.CoordinatorID;
  DropDownList_Update_BI_ComputerSystem.SelectedValue = Branch.ComputerSystemID;
  Text_Update_BI_Phone.Text = Branch.PhoneNumber;
  Text_Update_BI_Fax.Text = Branch.FaxNumber;

  Address BranchAddress = Branch.Contact.Addresses.FirstOrDefault();
  Text_Update_AI_House.Text = BranchAddress.HouseNumber;
  Text_Update_AI_Street.Text = BranchAddress.Street;
  Text_Update_AI_Area.Text = BranchAddress.Area;
  Text_Update_AI_Post.Text = BranchAddress.PostCode;
  DropDownList_Update_AI_City.SelectedValue = BranchAddress.City.OID;

  MaskedText_Update_OI_NoPharmacist.Value = Branch.NumberOfPharmacists;
  MaskedText_Update_OI_NoDispensers.Value = Branch.NumberOfDispensers;
  MaskedText_Update_OI_NoMonFri.Value = Branch.NumberOfItemsMondayToFriday;
  MaskedText_Update_OI_NoSat.Value = Branch.NumberOfItemsSaturday;
  MaskedText_Update_OI_NoSun.Value = Branch.NumberOfItemsSunday;
  MaskedText_Update_OI_NoAddicts.Value = Branch.NumberOfAddicts;
  MaskedText_Update_OI_NoSupervised.Value = Branch.Supervised;
  MaskedText_Update_OI_NoUnsupervised.Value = Branch.Unsupervised;

  Check_Update_OI_ConfRoom.Checked = Branch.ConsultationRoom;

  try {        
    PictureGoogleMaps.Image = GoogleAddressInfo.FetchMapInfo(Text_Update_AI_Post.Text).GoogleStaticMap;

  } catch (Exception) {
    PictureGoogleMaps.Image = Resources.DefaultGoogleMap;

  }
}

将图片加载到PictureGoogleMaps中的行会导致UI挂起,因为“。googleStaticMap”属性会在调用时生成Google静态图片。

在网上搜索时,我发现了这个有用的例子:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // Declare a list of URLs and their respective picture boxes
        var items = new Dictionary<string, PictureBox> 
        { 
            { "http://www.google.com/logos/spring09.gif", new PictureBox() { Top = 0, Width = 300, Height = 80  } }, 
            { "http://www.google.com/logos/stpatricks_d4gwinner_eo09.gif", new PictureBox() { Top = 100, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/schiaparelli09.gif", new PictureBox() { Top = 200, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/drseuss09.gif", new PictureBox() { Top = 300, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/valentines09.gif", new PictureBox() { Top = 400, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/unix1234567890.gif", new PictureBox() { Top = 500, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/charlesdarwin_09.gif", new PictureBox() { Top = 600, Width = 300, Height = 80 } },
        };

        foreach (var item in items)
        {
            var worker = new BackgroundWorker();
            worker.DoWork += (o, e) =>
            {
                // This function will be run on a background thread
                // spawned from the thread pool.
                using (var client = new WebClient())
                {
                    var pair = (KeyValuePair<string, PictureBox>)e.Argument;
                    e.Result = new KeyValuePair<PictureBox, byte[]>(pair.Value, client.DownloadData(pair.Key));
                }
            };
            worker.RunWorkerCompleted += (o, e) => 
            {
                // This function will be run on the main GUI thread
                var pair = (KeyValuePair<PictureBox, byte[]>)e.Result;
                using (var stream = new MemoryStream(pair.Value))
                {
                    pair.Key.Image = new Bitmap(stream);
                }
                Controls.Add(pair.Key);
            };
            worker.RunWorkerAsync(item);
        }
    }
}

现在我只需要弄清楚如何删除for循环并在我的场景中使用它。有什么想法吗?

示例代码来自此link

感谢。

2 个答案:

答案 0 :(得分:1)

去除foreach循环难吗?您只需要加载一张图片,然后删除foreach循环并将图片的网址和目标图片框传递给后台工作者。

答案 1 :(得分:1)

public partial class Form1 : Form
    {        
        private BackgroundWorker imageLoader;

        public Form1()
        {
            InitializeComponent();

            this.imageLoader = new BackgroundWorker();
            this.imageLoader.DoWork += HandleOnImageLoaderDoWork;
            this.imageLoader.RunWorkerCompleted += HandleImageLoaderOnRunWorkerCompleted;

            this.LoadUserDetails(1);
        }

        private void LoadUserDetails(Int32 userID)
        {
            this.imageLoader.RunWorkerAsync(userID.ToString());
            // get the user details
            // populate the UI controls with the data....
        }

        private void HandleImageLoaderOnRunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e)
        {
            this.pictureBox1.Image = (Image)e.Result;
        }

        private void HandleOnImageLoaderDoWork(Object sender, DoWorkEventArgs e)
        {
            // simulate a web request for an image;
            Thread.Sleep(3000);
            Image image = Image.FromFile(@"test.jpg");
            e.Result = image;
        }
    }

还要确保显示一些后台操作正在进行的UI通知...类似于PictureBox中的初始图像(loading.gif)。