В моем приложении, когда Button
нажатии на Command
запускается, что загружает image
(асинхронно .. я надеюсь) и strings
, name
и character
, указанные ниже. Функция для загрузки этих элементов вызывается из DispatcherTimer
как таковой:Are Timer and Task создает новые темы?
timer.Tick += myMethodToDownloadCastInfo;
В рамках этого метода у меня есть:
timer.Stop();
List<CastWithPic> castWithPicList = new List<CastWithPic>();
// Add name and id for each CastWithPic in the list
// ..
_viewModel.SelectedItem.castInfoWithPics = castWithPicList;
// Download all the required pics
var tasks = new List<Task>();
foreach (CastWithPic cast in castWithPicList)
{
tasks.Add(downloadBitmap(cast.profilePath, cast.id));
}
await Task.WhenAll(tasks);
В функции downloadBitmap
я установить объект SelectedItem's
castInfoWithPics
для хранения значения image
.
Именно в этот момент, что я получаю ошибку:
The calling thread cannot access this object because a different thread owns it.
SelectedItem
объявлен в моем ViewModel
.
SelectedItem
Класс
public List<CastWithPic> castInfoWithPics { get; set; }
CastWithPic
Класс
public string name
{
get { return (string)this.GetValue(nameProperty); }
set
{
this.SetValue(nameProperty, value);
}
}
public static readonly DependencyProperty nameProperty = DependencyProperty.Register(
"name", typeof(string),
typeof(CastWithPic));
public string character
{
get { return (string)this.GetValue(characterProperty); }
set
{
this.SetValue(characterProperty, value);
}
}
public static readonly DependencyProperty characterProperty = DependencyProperty.Register(
"character", typeof(string),
typeof(CastWithPic));
public Bitmap image
{
get { return (Bitmap)this.GetValue(imageProperty); }
set
{
this.SetValue(imageProperty, value);
}
}
public static readonly DependencyProperty imageProperty = DependencyProperty.Register(
"image", typeof(Bitmap),
typeof(CastWithPic));
downloadBitmap
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
RequestState myRequestState = new RequestState();
myRequestState.request = request;
// Start the asynchronous request.
IAsyncResult result = request.BeginGetResponse(new AsyncCallback(RespCallback), Tuple.Create(myRequestState, actorID));
// this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), request, DefaultTimeout, true);
// The response came in the allowed time. The work processing will happen in the
// callback function.
allDone.WaitOne();
Мой вопрос:
Почему я не получаю ошибку при назначении _viewModel.SelectedItem.castInfoWithPics = castWithPicList;
в методе timer
, но получаю ошибку в методе Task
.
Разве не timer
также есть новый thread
?
В этом случае это правильный способ решить проблему, чтобы использовать предлагаемое здесь решение?
The calling thread cannot access this object because a different thread owns it
Какая у вас функция 'downloadBitmap'? –
Привет @NedStoyanov, я добавил функцию 'downloadBitmap'. –
Где вы устанавливаете 'SelectedItem' это' RspCallback'? –