Dispatcher.BeginInvoke()不调用Action

时间:2013-09-17 11:42:41

标签: c# multithreading windows-phone-8 monogame adrotator

我正在使用MonoGame为Windows Phone 8构建游戏。它的免费版本将在顶部有广告。为了显示我正在使用AdRotator的广告。游戏可以选择将结果作为图像发布到Facebook。最近,在测试时我发现游戏在将图像发布到Facebook时完全冻结。在调试过程中,我能够检测到导致冻结的代码。此代码是MonoGame的一部分:

var waitEvent = new ManualResetEventSlim(false);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
    var bitmap = new WriteableBitmap(width, height);
    System.Buffer.BlockCopy(pixelData, 0, bitmap.Pixels, 0, pixelData.Length);
    bitmap.SaveJpeg(stream, width, height, 0, 100);
    waitEvent.Set();
});

waitEvent.Wait();

因此,MonoGame线程正在等待设置 waitEvent ,但BeginInvoke不会调用操作。当没有AdControl时,一切都很好,所以对我而言,看起来AdRotator和MonoGame在某种程度上是冲突的,但我真的不明白为什么会发生这种情况。

UPD:调用上面代码的代码示例

RenderTarget2D renderTarget = new RenderTarget2D(ScreenManager.GraphicsDevice, width, height, false, SurfaceFormat.Color, DepthFormat.Depth24);

ScreenManager.GraphicsDevice.SetRenderTarget(renderTarget);
ScreenManager.GraphicsDevice.Clear(Color.White);

SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
spriteBatch.Begin();

// drawing some graphics

spriteBatch.End();

ScreenManager.GraphicsDevice.SetRenderTarget(null);

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
     using (var stream = store.OpenFile(FacebookShareFileName, FileMode.Create, FileAccess.ReadWrite))
     {
         renderTarget.SaveAsJpeg(stream, width, height);
     }
}

所以游戏冻结了

renderTarget.SaveAsJpeg(stream, width, height);

1 个答案:

答案 0 :(得分:0)

试试这个,

将同步上下文传递给方法。

SynchronizationContext uiThread = SynchronizationContext.Current;

    public WritableBitmap GetImage(SynchronizationContext uiThread))
    {
        WriteableBitmap bitmap = null;
        var waitHandle = new object();
        lock (waitHandle)
        {
            uiThread.Post(_ => 
            {
                lock (waitHandle)
                {
                   bitmap = new WriteableBitmap(width, height);
                   System.Buffer.BlockCopy(pixelData, 0, bitmap.Pixels, 0, pixelData.Length);
                   bitmap.SaveJpeg(stream, width, height, 0, 100);
                   Monitor.Pulse(waitHandle);
                }

            }, null);

            Monitor.Wait(waitHandle);
        }
        return bitmap;
   }

并在另一个线程中调用此方法;

        SynchronizationContext uiThread = SynchronizationContext.Current;
        var result = await Task.Factory.StartNew<WriteableBitmap>(() =>
        {
            return GetImage(uiThread);
        });

我没有将 pixelData 您的像素数组添加到代码中。您可以将该信息传递给您的代码。我也是从头脑中输入代码,而不是在VS编辑器中测试过。所以你可能会发现一些错别字,请你忽略它。希望这能解决您的问题。享受编码