How to perform operation on a background thread

2019-09-20 11:29发布

问题:

I am working on Silverlight project based on MVVM architechture. on click of a button a c# linq query gets executed which takes some time to execute (about one and half minute) due to which my UI hangs for this much time untill the response is received.

I'm having a custom progress bar which needs to be shown in between. I tried to execute this linq statement on a background thread but no success.

Current Code:

private void _selectRecords()
{
    //linq-query
}

I tried below steps,

private void _selectRecords()
{
    System.Threading.Thread worker = new System.Threading.Thread(GetData);
            worker.Start();
}

private void GetData()
{
    //linq-query
}

EDIT : in above case while execution getting Exception Invalid cross-thread access.

and

private void _selectRecords()
{
    System.Threading.Thread worker = new System.Threading.Thread(GetData);
            worker.Start();
}

private void GetData()
{
   ApplicationConstants.AppConstants.WaitCursor = true; //MY PROGRESS BAR
    Deployment.current.Dispatcher.BeginInvoke(()=>{
                //linq-query        
        });

}

how can i run this linq statement on a background thread?

回答1:

How about using BackgroundWorker

Declare a backgroundworker variable like this in your view Class

BackgroundWorker _worker;

in the constructor of your view initiate a Backgroundworker like this

    _worker = new BackgroundWorker();
    _worker.DoWork += new DoWorkEventHandler(_worker_DoWork);
    _worker.ProgressChanged += new ProgressChangedEventHandler(_worker_ProgressChanged);

void _worker_DoWork(object sender, DoWorkEventArgs e)
{
   //call your getdata() method here
    GetData();

}

In button click you can start this backgroundworker like this

m_oWorker.RunWorkerAsync();

Using Progress Changed Event handler you can show the progress to the user

_worker_ProgressChanged

I just tried to incorporate your code into something like this