代码冻结了我的应用程序

时间:2012-04-13 18:52:45

标签: c# .net wpf screenshot

此代码极端冻结了WPF应用程序。

有没有机会解决它?

var getScreenshot = Task.Factory.StartNew(() => 
{                       
    Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new ThreadStart(() => {                        
    #region Main
    try
    {
        Graphics gfx;
        Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
        gfx = Graphics.FromImage(bmp);
        WindowInteropHelper windowInteropHelper = new WindowInteropHelper(this);
        Screen screen = Screen.FromHandle(windowInteropHelper.Handle);
        gfx.CopyFromScreen(screen.Bounds.X, screen.Bounds.Y, 0, 0, screen.Bounds.Size, CopyPixelOperation.SourceCopy);
         MemoryStream ms = new MemoryStream();
        byte[] bitmapData = null;
        using (bmp)
        {
            bmp.SetResolution(72, 72);
            ImageCodecInfo myImageCodecInfo;
            myImageCodecInfo = GetEncoderInfo("image/jpeg");
            System.Drawing.Imaging.Encoder myEncoder;
            myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters encoderParameters = new EncoderParameters();
            EncoderParameter encoderParameter = new EncoderParameter(myEncoder, 25L);
            encoderParameters.Param[0] = encoderParameter;
            bmp.Save(ms, myImageCodecInfo, encoderParameters);                               
            bitmapData = ms.ToArray();
        }
        if (bitmapData != null)
            DataProvider.UpdateScreen(((PlayerConfiguration)App.Current.Properties["PlayerConfig"]).InstallationKey, bitmapData);
    }
    catch (Exception ex)
    {
        #region Error
        LogEntry l = new LogEntry();
        l.Message = string.Format("{0}", ex.Message);
        l.Title = "GetScreen() Error";
        l.Categories.Add(Category.General);
        l.Priority = Priority.Highest;

        CustomLogger.WriteErrorLog(l, "GetScreen");

        #endregion
    }
    #endregion
  }));

}, TaskCreationOptions.LongRunning)
.ContinueWith(x => x.Dispose()); 

1 个答案:

答案 0 :(得分:3)

是的,只是不要为整个事情调度到UI线程。只需将最少量的代码放入您可以使用的Invoke调用中。它应该是您实际更新UI时。由于整个事情都在代码中的调用调用中,因此UI被阻塞,直到整个事情结束。