GeekInterview.com
  I am new, Sign me up!
 
GeekInterview.com  >  Interview Questions  >  Microsoft  >  C#
Go To First  |  Previous Question  |  Next Question 
 C#  |  Question 414 of 436    Print  
Threading
Write a very simple multi threaded program in C#.
1. The program should create two threads that each add data to the same list at the same time. Then after they are both done, print out the entire list.
2. So each thread should loop through 100 times adding the name of the thread doing the work to the list. For example, the first thread should add the string "thread1" to the shared list and the second thread should add the string "thread2" to the same list at the same time. This should result in a somewhat random ordering of the names "thread1" and "thread2" in the shared list that is printed out after both threads complete.
3. When a thread adds a name it should also print out its name and the current count of the list.
4. Make sure that each individual name addition is not interrupted by the other thread.



  
Total Answers and Comments: 2 Last Update: May 17, 2008     Asked by: musclebai 
  
 Sponsored Links

 
 Best Rated Answer

No best answer available. Please pick the good answer available or submit your answer.
March 15, 2008 03:15:16   #1  
yogihanu Member Since: March 2008   Contribution: 1    

RE: Threading
Copy and past the below mentioned code to get the answer:

++++++++++
//Start copy from here

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;

namespace ThreadTest
{
class Program
{
static ArrayList alist new ArrayList();

static void Main(string[] args)
{
//ArrayList alist new ArrayList();
ThreadStart job1 new ThreadStart(Threadjob1);
ThreadStart job2 new ThreadStart(Threadjob2);
Thread th1 new Thread(job1);
Thread th2 new Thread(job2);
th1.Start();
th2.Start();

int i 0;
while (i < 10)
{
Console.WriteLine("Main Thread 1 : {0}" i);
alist.Add(string.Format("MainThread - {0}" i));
Thread.Sleep(1000);
i++;
}
for (int j 0; j < alist.Count-1; j++)
{
Console.WriteLine("Name : {0}ttIndex : {1}" alist[j] j);
}
Console.Read();

}
static void Threadjob1()
{
int i 0;
while (i < 10)
{
Console.WriteLine("J O B 1 : {0}" i);
alist.Add(string.Format("Job1 - {0}" i));
Thread.Sleep(200);
i++;
}

}
static void Threadjob2()
{
int i 0;
while (i < 10)
{
Console.WriteLine("J O B 2 : {0}" i);
alist.Add(string.Format("Job2 - {0}" i));
Thread.Sleep(500);
i++;
}
}
}
}
//End copy here

 
Is this answer useful? Yes | No
May 17, 2008 07:55:22   #2  
JimmyJamJo Member Since: April 2007   Contribution: 2    

RE: Threading
See code below. In practice the Thread.Sleep() is required - otherwise each thread will complete its work in a single time-slice before the other gets a chance to start. An improvement would be to create a "work item" class for the that would wrap "outputList" and "repeatCount" together in a single object and use that with the ParameterizedThreadStart delegate.

-

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;

public class MyApp
{
private static IList<string> outputList new List<string>();

static void Main()
{
const int threadCount 2;
const int repeatCount 100;

Thread[] threadList new Thread[threadCount];

// Create and start threads
for (int i 0; i < threadCount; i++)
{
threadList[i] new Thread(new ParameterizedThreadStart(DoWork));
threadList[i].Name String.Format(CultureInfo.InvariantCulture "Thread{0}" i);
threadList[i].Start(repeatCount);
}

// Wait for them to do the business
foreach (Thread t in threadList)
{
t.Join();
}

Console.WriteLine("All threads complete");

// Output
foreach (string s in outputList)
{
Console.WriteLine(s);
}
}

private static void DoWork(object repeatCount)
{
Thread thisThread Thread.CurrentThread;
int numberOfWrites (int)repeatCount;
for (int i 0; i < numberOfWrites; i++)
{
int listCount 0;
lock (outputList)
{
outputList.Add(thisThread.Name);
listCount outputList.Count;
}

Console.WriteLine("{0} - list count {1}" thisThread.Name listCount);

// Sleep this thread to give the other thread(s) a fighting chance to get
// in on the action
Thread.Sleep(10);
}
}
}

 
Is this answer useful? Yes | No

 Related Questions

C# requires only a single parameter for delegates: the method address. Unlike other languages, where the programmer must specify an object reference and the method to invoke, C# can infer both pieces of 
Latest Answer : This article is good.IntroductionIn this article I am going to share my knowledge on Delegates in C#.This would explain the Delegate using simple examples so that the beginner can understand the same.What is Delegate?Definition:Delegate is type which ...

Some sample code follows: using System;using System.Threading;class ThreadTest {public void runme() {Console.WriteLine("Runme Called");} public static void Main(String[] args) {ThreadTest b = 
Latest Answer : Ans:using System;using System.Threading;class ThreadTest {public void runme() {Console.WriteLine("Runme Called");} public static void Main(String[] args) {ThreadTest b = new ThreadTest();Thread t = new Thread(new ThreadStart(b.runme));t.Start();}} ...

.NET FRAMEWORK1. What is .NET Framework?The .NET Framework has two main components: the common language runtime and the .NET Framework class library.You can think of the runtime as an agent that manages 
Latest Answer : The .NET framework is a platform over which multiple languages are running.The 2 main components are 1. FRAMEWORK CLASS LIBRARY2. COMMON LANGUAGE RUNTIMEIt's features like CTS provide Cross Language Interoprabality.The CLR is the main Governing body ...
Read Answers (1) | Asked by : Prasanna Muthukrishnan

Write a very simple multi threaded program in C#. 1. The program should create two threads that each add data to the same list at the same time. Then after they are both done, print out the entire list. 
Latest Answer : See code below. In practice, the Thread.Sleep() is required - otherwise each thread will complete its work in a single time-slice before the other gets a chance to start. An improvement would be to create a "work item" class for the that would ...


 Sponsored Links

 
Related Articles

The Interview Snafu

How to turn someone else&rsquo;s mistake to your advantage Your dream job is about to become reality. A recruiter gave you the heads up about the perfect position at Humungous Conglomerate, Inc. You went through five interviews as well as a battery of psychological tests mandated by their HR de
 

Winning a Job Interview with a Winning Resume

Does your resume unlock your potential, take your skills to the highest level and win you the interview and the job you want now? The job market today is highly competitive and even if you think you have what it takes to get an interview you won&rsquo;t get over the line without a polished, prof
 

Importance of Proper English during Job Interview

Importance of Proper English during Job Interview Your job interview is crucially important and it will determine whether or not you will get the job Depending on the type of job you re going for it is very important for you to use proper English In most cases jobs which offer higher salaries will h
 

HR Interview - HR Interview Mistakes You Will Want To Avoid

HR Interview Mistakes You Will Want To Avoid The job interview can be a stressful process This is especially true for those who are going after a competitive position Your nonverbal communication combined with the answers you give during the interview will determine if you are hired mosgoogle While
 

HR Interview - Behavioral HR Interviews

Behavioral HR Interviews As the name implies a behavioral interview is an interview that is held by a human resources department to determine if an applicant has the behaviors that are appropriate for a job The company must know how an applicant will behave in a certain situations mosgoogle The logi
 

HR Interview - How To Prepare For Your HR Interview

How To Prepare For Your HR Interview Before you begin thinking about how you are going to dress for the interview it is important to do your research first You should learn everything you can about the company you wish to work for When you have detailed information about your employer you will conve
 

HR Interview - Telephone Interview Etiquette

Telephone Interview Etiquette When you conduct a telephone interview for a job it is important to show the proper etiquette Not only is it important it is critical is you wish to be hired by the company There are a number of things you will want to do and other things should never be done mosgoogle
 

HR Interview - How To Succeed At HR Interviews

How To Succeed At HR Interviews There are a number of things you will need to do in order to make sure you pass the interview process Your appearance is something that you will want to pay close attention to Even if you feel that your appearance shouldn t be a factor in whether or not you re highere
 

HR Interview - Do's and Dont's in a HR Interview

Do s and Dont s in a HR Interview There are a number of things that you will want to avoid during the HR interview process While some of these things are directed at the interviewer the other things are directed at the applicant If interviewers fail to follow the proper procedures throughout the int
 

HR Interview - HR Interview Tips

HR Interview Tips It has become more challenging for companies to find the right employees because of the market When you hold an interview for a potential employee there are a number of things you will want to keep in mind mosgoogle The goal of a company should be to hire an employee who can perfor
 

About Us -  Privacy Policy -  Terms and Conditions -  Contact -  Ask Question -  Propose Category -  Site Updates 

Copyright © 2005 - 2009 GeekInterview.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape