Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

c# - How to perform operation on a background thread

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...