开发者

multithreading in c# compact framework

开发者 https://www.devze.com 2022-12-08 18:14 出处:网络
i am using compact frame work for my windows mobile application in which i have pass more than one request to the server and receive response for each request in an array.

i am using compact frame work for my windows mobile application in which i have pass more than one request to the server and receive response for each request in an array.

the problem is there when i should access these arrays because i m starting the threads in a for loop and the after completing the loop i have to access these arrays.

i m very much confused in, how will i know 开发者_如何转开发and that all threads have completed so that i start the processing on these arrays

help is require asap. please.


How about this:

private readonly object syncRoot = new object();
private object[] responses;

public void StartThreads(int numberOfThreads)
{
    this.responses = new object[numberOfThreads];

    List<Thread> threads = new List<Thread>();
    for (int i = 0; i < numberOfThreads; ++i)
    {
        Thread thread = new Thread(this.DoWork);
        thread.Name = i.ToString();
        threads.Add(thread);
        thread.Start();
    }

    foreach (Thread thread in threads)
    {
        thread.Join();
    }

    // all threads are done.
}

private void DoWork()
{
    // do web call
    // object response = web.GetResponse();
    int threadNumber = Convert.ToInt32(Thread.CurrentThread.Name);
    lock (this.syncRoot)
    {
        this.responses[threadNumber] = response;
    }
}


//Declare this in class
public delegate void delege();

//Write this lines when you want to background thread start
    Thread thread = new Thread(new ThreadStart(() => {
    //Do what you what with backgorund threading , can not use any interface comand here
         BeginInvoke(new delege(() => { 
           //Do here any main thread thread job,this can do interface and control jobs without any error 
         }));
    }));
    thread.Start();
0

精彩评论

暂无评论...
验证码 换一张
取 消