NoWar
NoWar

Reputation: 37662

Code freezes my application

This code extremly freezes the WPF application.

Is there ANY chance to fix it?

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()); 

Upvotes: 0

Views: 197

Answers (1)

Servy
Servy

Reputation: 203839

Yes, just don't dispatch to the UI thread for the whole thing. Only put the smallest amount of code into the Invoke call that you can get away with. It should be when you're actually updating the UI. Since the whole thing is in the invoke call in your code, the UI is blocked until the whole thing finishes.

Upvotes: 3

Related Questions