Sunday 26 September 2021

Tasks and Threads

 Differences Between Task And Thread:


1. The Thread class is used for creating and manipulating a thread in Windows. 

2. A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel.

3. The task can return a result. There is no direct mechanism to return the result from a thread.

4. Task supports cancellation through the use of cancellation tokens. But Thread doesn't.

5. A task can have multiple processes happening at the same time. Threads can only have one task running at a time. We can easily implement Asynchronous using ’async’ and ‘await’ keywords.

6. A new Thread()is not dealing with Thread pool thread, whereas Task does use thread pool thread.

7. A Task is a higher level concept than Thread.



Sample for task with return result:

namespace TaskWithReturnResult

{

    /// <summary>

    /// The task can return a result. There is no direct mechanism to return the result from a thread.

    /// </summary>

    class Program

    {

        static void Main(string[] args)

        {

            var _rectangles = new List<Rectangle>()

            {

                new Rectangle(10,15),

                new Rectangle(6,14),

                new Rectangle(18,45),

                new Rectangle(3,8),

                new Rectangle(20,9),

                new Rectangle(30,4),

                new Rectangle(40,17),

                new Rectangle(3,25),

                new Rectangle(2,35),

                new Rectangle(1,28)

            }; 

            var task = new Task<Rectangle>(() => GetMaxPeremetrRect(_rectangles));

            task.Start();

            task.Wait();

            System.Console.WriteLine(task.Result.Peremetr());

            System.Console.ReadLine();


        }


        private static Rectangle GetMaxPeremetrRect(IList<Rectangle> rectangles)

        {

            if (rectangles.Count == 0)

                return default;


            var result = rectangles[0];

            foreach (var item in rectangles)

            {

                if (result.Peremetr() < item.Peremetr())

                    result = item;

            }


            return result;

        }

        

    }

    public class Rectangle

    {

        private double width;

        private double height;

        public Rectangle(double width, double height)

        {

            this.width = width;

            this.height = height;

        }

        public double Peremetr()

        {

            return 2 * (width + height);

        }

    }

}


Monday 4 February 2019

Using Builder pattern in C#


Builder Pattern Sample in C#

Builder pattern – ob’ektlarni qadamba-qadam yaratishga mo’ljallangan patterndir.

Masalan har bir kitobning Id, Name, Author nomli xususiyatlari uchun BookBuilder qanday realizatsiya qilinishini ko’ramiz
public sealed class Book
    {
        private readonly int id;
        private readonly string name;
        private readonly string author;
        public Book(int id, string name,string author)
        {
            this.id = id;
            this.name = name;
            this.author = author;
        }
        public string GetInfo()
        {
            return $"Book INFO: id:{id}, name: {name}, author:{author}";
        }
    }

Endi BookBuilder classini realizatsiya qilamiz:

public sealed class BookBuilder : IBookBuilderSetId, IBookBuilderSetName, IBookBuilderSetAuthor, IBookBuilder
    {
        private int id;
        private string name;
        private string author;
        private BookBuilder() { }
        public static IBookBuilderSetId CreateNew()
        {
            return new BookBuilder();
        }

       

        public IBookBuilderSetName SetId(int id)
        {
            this.id = id;
            return this;
        }


        public IBookBuilderSetAuthor SetName(string name)
        {
            this.name = name;
            return this;
        }

        public IBookBuilder SetAuthor(string author)
        {
            this.author = author;
            return this;
        }

        public Book Build()
        {
            return new Book(id, name, author);
        }
    }



    public interface IBookBuilderSetId
    {
        IBookBuilderSetName SetId(int id);
    }

    public interface IBookBuilderSetName
    {
        IBookBuilderSetAuthor SetName(string name);
    }

    public interface IBookBuilderSetAuthor
    {
        IBookBuilder SetAuthor(string author);
    }

    public interface IBookBuilder
    {
        Book Build();
    }


Ishlatilishi:

static void Main(string[] args)
{
    Book myBook = BookBuilder.CreateNew()
    .SetId(10)
    .SetName("Learning .Net Core")
    .SetAuthor("Mike Tyson")
    .Build();
    System.Console.WriteLine(myBook.GetInfo());
    System.Console.ReadLine();
}

Natijasi:
Book INFO: id:10, name: Learning .Net Core, author: Mike Tyson



Saturday 8 April 2017

Canvas - accept mousewheel events (WPF)

WPF da Canvas ning MouseWheel eventini handle qilish
 
  Odatda Canvas yaratib, unga ixtiyoriyta Children add qilganimizda
  va undagi MouseWheel eventini qayta ishlashimiz uchun:
     canvas1.Background = Brushes.Transparent; deb olishimiz yoki umumiy olganda
     yaratgan canvas1 objectimizning Background qiymatini o'rnatishimiz kerak;
aks holda MouseWheel event ni hadle qila olmaymiz. Chunki default holatda
Canvas Background siz yaratiladi.
Masalan:
 
  ...

  Canvas canvas1 = new Canvas();
  canvas1.Background = Brushes.Transparent;
  Label label = new Label();
  label.Content = "This is Text";
  label.Foreground = Brushes.Blue;
       label.FontSize = 12;
       label.FontWeight = FontWeights.Bold;
  canvas1.Children.add(label);
  canvas1.MouseWheel+=Canvas1_Mouseheel;
  ...
  void Canvas1_Mouseheel()
  {
  ...
  }

Using Column and Row deffinations in WPF


WPF da Column va Row deffination lardan foydalanish

Window da ishlaganimizda yoki UserControlda ishlaganimizda
uni Row va Column larga ajratgan holda contentlarni joylashtirishimiz mumkin
buning uchun Grid quyidagi tartibda aniqlanishi lozim:
   <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="400" Name="column1"/>
            <ColumnDefinition Width="*" Name="column2"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
</Grid>

Ushubu code yordamida biz Grid ni 2ta Column va 1ta Row ga ajratib yaratdik.
Endi Ixtiyoriy elementni add qilishni qaraymiz. Row yoki Column lar avtomatik
0 dan boshlab indexlangan boladi.

...
<Button x:Name="btnResult" Content="Результать" HorizontalAlignment="Left" Margin="78,16,0,0" VerticalAlignment="Top" Width="75" Click="btnResult_Click"
                Grid.Column="0"/>
<Button x:Name="btnReport" Content="Отчёть" HorizontalAlignment="Left" Margin="78,16,0,0" VerticalAlignment="Top" Width="75" Click="btnReport_Click"
                Grid.Column="1"/>
...

Demak, yuqoridagi code ning ma'nosi shundaki,
btnResult tugmasi 1-columnga add qilindi, btnResult esa 2-Column ga add qilindi.

Bu nima uchun kerak?
 Biz Grid ni Column va Row lar yordamida xoxlagancha bolaklarga ajaratib har bir yacheykasiga content joylashtira olamiz!
Savol: Yacheykalarga Splitter qoyish mumkinmi? Ya'ni mouse bilan uning sizeni change qiboladimi?
 Javob: Albatta boladi!
Masalan:
 <Window x:Class="MySamples.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplicationSample2"
        mc:Ignorable="d"
        Title="MainWindow" Height="728" Width="1024" WindowStartupLocation="CenterScreen"
        WindowState="Maximized">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="400" Name="column1"/>
            <ColumnDefinition Width="*" Name="column2"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>      
       
        <Button x:Name="btnResult" Content="Результать" HorizontalAlignment="Left" Margin="78,16,0,0" VerticalAlignment="Top" Width="75" Click="btnResult_Click"
                Grid.Column="0"/>
        <ListBox Name="listBox1" Margin="0,50,0,0"
                 ItemsSource="{Binding Items}" Grid.Column="0" Width="380" Height="650">
            <ListBox.ItemTemplate>
                <DataTemplate>

                    <StackPanel Orientation="Horizontal" Background="Aqua">
                        <Label Content="{Binding recNo}" Width="100"/>
                        <Button Content="{Binding Path=wellName}" Width="120" Background="AliceBlue"/>
                        <Button>
                            <Button.Content>
                                <TextBlock Text="{Binding Path=x0, StringFormat='X: {0}'}" Width="70"/>
                            </Button.Content>
                        </Button>
                        <Button>
                            <Button.Content>
                                <TextBlock Text="{Binding Path=y0, StringFormat='Y: {0}'}" Width="70"/>
                            </Button.Content>
                        </Button>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <GridSplitter Grid.Column="0"
                        HorizontalAlignment="Right"
                        Background="Green"
                        ShowsPreview="False"
                        Width="5" Height="Auto"/>
        <TextBlock Text="this is second block" Grid.Column="1" Margin="10,0,0,0"/>
        <ScrollViewer Grid.Column="1" CanContentScroll="True" Margin="0,0,0,0"
                      HorizontalAlignment="Left" VerticalAlignment="Top" VerticalScrollBarVisibility="Auto"
                      HorizontalScrollBarVisibility="Auto">

            <Canvas Name="canvas1" Grid.Column="1" Width="1500" Height="950" HorizontalAlignment="Left"
                    VerticalAlignment="Top" Margin="0,0,0,0">
            </Canvas>
        </ScrollViewer>
    </Grid>
</Window>
 

Wednesday 1 March 2017

toString() in Java



Java toString() metodi

Ixtiyoriy ob’yektni string(satr) ko’rinishida ifodalash uchun doimo toString() metodidan foydalanamiz
toString() metodi ob’yektning satr ko’rinishini qaytaradi. Ixtiyoriy ob’yektni chop qilganimizda Java kompilyatori ob’ekt ichidagi toString() metodini ishlatadi. Agar toString() metodi overrid qilinmagan bo’lsa obektning byte ko’rinishi chop qilinadi. toString() metodini overrid qilish orqali ob’ekt haqidagi kerakli ma’lumotlarni qaytarishimiz mumkin.
Misollar:
#1. toString() metodini overrid qilmasdan ob’ektni chop qilish
Book.java:

/**
 * Created by Mansurjon on 3/1/2017.
 */
public class Book {
   
private int id;
   
private String name;
   
private String author;
   
private float price;

   
public int getId() {
       
return id;
    }

   
public void setId(int id) {
       
this.id = id;
    }

   
public String getName() {
       
return name;
    }

   
public void setName(String name) {
       
this.name = name;
    }

   
public String getAuthor() {
       
return author;
    }

   
public void setAuthor(String author) {
       
this.author = author;
    }

   
public float getPrice() {
       
return price;
    }

   
public void setPrice(float price) {
       
this.price = price;
    }

   
public Book(int id, String name, String author, float price) {
       
this.id = id;
       
this.name = name;
       
this.author = author;
       
this.price = price;
    }
}
BookMain.java
package tostring;

/**
 * Created by Mansurjon on 3/1/2017.
 */
public class BookMain {
   
public static void main(String[] args) {
        Book book =
new Book(1,"Философия Java", "B.Ekkel", 82);
        System.
out.println(book);

    }

}
Natija:
Book@1c63996


#2. toString() metodini overrid qilish
Book.java:
package tostring;

/**
 * Created by Mansurjon on 3/1/2017.
 */
public class Book {
   
private int id;
   
private String name;
   
private String author;
   
private float price;

   
public int getId() {
       
return id;
    }

   
public void setId(int id) {
       
this.id = id;
    }

   
public String getName() {
       
return name;
    }

   
public void setName(String name) {
       
this.name = name;
    }

   
public String getAuthor() {
       
return author;
    }

   
public void setAuthor(String author) {
       
this.author = author;
    }

   
public float getPrice() {
       
return price;
    }

   
public void setPrice(float price) {
       
this.price = price;
    }

   
public Book(int id, String name, String author, float price) {
       
this.id = id;
       
this.name = name;
       
this.author = author;
       
this.price = price;
    }

   
@Override
   
public String toString() {
       
return "Kitob haqida ma'lumotlar: {" +
               
"id=" + id +
               
", name='" + name + '\'' +
               
", author='" + author + '\'' +
               
", price=" + price +
                
'}';
    }
}

BookMain.java
BookMain.java
package tostring;

/**
 * Created by Mansurjon on 3/1/2017.
 */
public class BookMain {
   
public static void main(String[] args) {
        Book book =
new Book(1,"Философия Java", "B.Ekkel", 82);
        System.
out.println(book);

    }

}
Natija:
Kitob haqida ma'lumotlar: {id=1, name='Философия Java', author='B.Ekkel', price=82.0}


Tasks and Threads

  Differences Between Task And Thread: 1. The Thread class is used for creating and manipulating a thread in Windows.  2. A Task represents ...