Cross-thread operation not valid:....

saeedtahrirchisaeedtahrirchi USMember
edited June 2014 in Xamarin.Forms

Hi
in code :
`
t1=new Thread(new ThreadStart(FillDropDownDesk));
t1.Start();

private void FillDropDownDesk()
{
if (!CheckConnection())
return;
TableClass table = new TableClass();
DropDown.Adapter = table.GetNameTableFree(this);
IDs = table.GetIdTableFree();
btnSave.Enabled = true;
progress.Dismiss();
}
`
Error show "Cross-thread operation not valid:...."
pelese Help

Posts

  • rmarinhormarinho PTMember, Insider, Beta Xamurai
    edited June 2014

    I think you are accessing something that's living in the UI Thread, you have to switch back to the main thread or turn that code into to async/await so you could do something like:

    var result = await CheckConnection();
    if(result){
    TableClass table = new TableClass(); 
    DropDown.Adapter = table.GetNameTableFree(this); 
    IDs = table.GetIdTableFree(); btnSave.Enabled = true; progress.Dismiss();
    }
    

    This way after you 'await' you will be back on the ui Thread.

  • saeedtahrirchisaeedtahrirchi USMember

    When I remove the following code solved my problem:

    DropDown.Adapter = table.GetNameTableFree(this);
    btnSave.Enabled = true;

    I need the code in Thrad
    Please help

  • MihaMarkicMihaMarkic SI ✭✭✭✭

    Why don't you try what rmarinho suggested? You have cross threading issues and his solution would solve them and still keep your thread. I'd just slightly modify it:

    public async Task GetDataAsync() { if (!CheckConnection()) return; TableClass table = new TableClass(); DropDown.Adapter = await Task.Factory.StartNew(() => table.GetNameTableFree(this)}; IDs = await Task.Factory.StartNew(() => table.GetIdTableFree()}; btnSave.Enabled = true; progress.Dismiss(); } }

Sign In or Register to comment.