0

此代码极度冻结 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()); 
4

1 回答 1

3

是的,只是不要为整个事情分派给 UI 线程。只将最少量的代码放入Invoke您可以逃脱的调用中。应该是在您实际更新 UI 时。由于整个事情都在代码中的调用调用中,因此 UI 被阻塞,直到整个事情完成。

于 2012-04-13T18:56:54.367 回答