Tuesday, February 21, 2012

[Solution] WP7: UnauthorizedAccessException with "Invalid cross-thread access" message

Symptoms

UnauthorizedAccessException exception with "Invalid cross-thread access" message is raised when accessing UI classes from OnInvoke method of a periodic task, e.g. when creating a live tile background image with WriteableBitmap.SaveJpeg.

Same exception is raised when accessing UI classes from a background thread (e.g. when using BackgroundWorker) or from any other async callback (e.g. WebRequest.BeginGetResponse).

Explanation

Any actions that will affect the UI must be executed from the UI thread.

Solution

Use Deployment.Current.Dispatcher.BeginInvoke method to execute your code on the UI thread.

public class ScheduledAgent : ScheduledTaskAgent
{
    ...
    
    protected override void OnInvoke(ScheduledTask task)
    {
        Deployment.Current.Dispatcher.BeginInvoke(UiThreadFunc);
    }

    private void UiThreadFunc()
    {
        Canvas canvas = new Canvas();

        ...

        WriteableBitmap writeableBitmap = new WriteableBitmap(173, 173);
        writeableBitmap.Render(canvas, null);
        writeableBitmap.Invalidate();

        using (IsolatedStorageFileStream isolatedStorageFileStream =
            IsolatedStorageFile.GetUserStoreForApplication().CreateFile("/Shared/ShellContent/TileBackground.jpg"))
        {
            writeableBitmap.SaveJpeg(isolatedStorageFileStream, 173, 173, 0, 100);
        }

        ...
    }
}

No comments:

Post a Comment