1

I try run code analyses in visual studio, an I get this warning:

Warning 22 CA2000 : Microsoft.Reliability : In method 'MessengerViewModel.GoToRoom()', call System.IDisposable.Dispose on object 'new Task(CS$<>9__CachedAnonymousMethodDelegate6)' before all references to it are out of scope. C:\Users\Jan\Documents\Visual Studio 2010\Projects\C#\Pokec_Messenger_Project\Pokec_Messenger\Spirit_Caliburn_Micro_v1.0\ViewModels\MessengerViewModel_MainMenu.cs 45 Spirit_Caliburn_Micro_v1.0

on this method:

    public void GoToRoom()
    {
        try
        {
            new System.Threading.Tasks.Task(() =>
            {
                Service.GoToRoom(Account, SelectedRoom);
                Service.LoadRoomMsg(Account, SelectedRoom);
            }
            ).Start();
        }
        catch (Exception exception)
        {
            MsgBox.ShowException(exception);
        }

    }

I don’t understand on which object I should call Dispose method.

Edited:

I try this:

    public void GoToRoom()
    {
        Task task = null;
        try
        {
            task = new Task(() =>
            {
                Service.GoToRoom(Account, SelectedRoom);
                Service.LoadRoomMsg(Account, SelectedRoom);
            });
            task.Start();
        }
        catch (Exception exception)
        {
            MsgBox.ShowException(exception);
        }
        finally
        {
            if (task != null)
                if (task.Status == TaskStatus.RanToCompletion ||
                    task.Status == TaskStatus.Faulted ||
                    task.Status == TaskStatus.Canceled)
                    task.Dispose();
        }
    }

Run code analyses and get:

Warning 21  CA2000 : Microsoft.Reliability : In method 'MessengerViewModel.GoToRoom()', call System.IDisposable.Dispose on object 'task' before all references to it are out of scope.  C:\Users\Jan\Documents\Visual Studio 2010\Projects\C#\Pokec_Messenger_Project\Pokec_Messenger\Spirit_Caliburn_Micro_v1.0\ViewModels\MessengerViewModel_MainMenu.cs  59  Spirit_Caliburn_Micro_v1.0
  • The Thread class has disposable resources but the original designers were brave enough to not let it inherit IDisposable. Next to impossible to use. Pretty close to true for Task as well, although it has the additional burden of having to deal with Task.Exception. – Hans Passant Feb 07 '11 at 21:09

1 Answers1

1

It is wanting you to call dispose on Task. See this explanation as to why.

More information can be found on this topic here

Community
  • 1
  • 1
esac
  • 24,099
  • 38
  • 122
  • 179