Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > .NET Frameworks (точка нет фреймворки) > C# (си шарп)
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 02.04.2011, 04:42   #1
Nicrom
 
Регистрация: 02.04.2011
Сообщений: 3
По умолчанию Перевести в С#

Помогите пожалуйста перевести в C#. Исходник если я не ошибаюсь в VB.NET. Описана взаимная блокировка потоков.
Код:
1 Option Strict On
2 Imports System.Threading
3 Module Modulel
4 Sub Main()
5 Dim Tom As New Programmer( "Tom")
6 Dim Bob As New Programmer( "Bob")
7 Dim aThreadStart As New ThreadStart(AddressOf Tom.Eat)
8 Dim aThread As New Thread(aThreadStart)
9 aThread.Name= "Tom"
10 Dim bThreadStart As New ThreadStarttAddressOf Bob.Eat)
11 Dim bThread As New Thread(bThreadStart)
12 bThread.Name = "Bob"
13 aThread.Start()
14 bThread.Start()
15 End Sub
16 End Module
17 Public Class Fork
18 Private Shared mForkAvaiTable As Boolean = True
19 Private Shared mOwner As String = "Nobody"
20 Private Readonly Property OwnsUtensil() As String
21 Get
22 Return mOwner
23 End Get
24 End Property
25 Public Sub GrabForktByVal a As Programmer)
26 Console.Writel_ine(Thread.CurrentThread.Name &_ 
"trying to grab the fork.")
27 Console.WriteLine(Me.OwnsUtensil & "has the fork.") . .
28 Monitor.Enter(Me) 'SyncLock (aFork)'
29 If mForkAvailable Then
30 a.HasFork = True
31 mOwner = a.MyName
32 mForkAvailable = False
33 Console.WriteLine(a.MyName&"just got the fork.waiting")
34 Try
Thread.Sleep(100) Catch e As Exception Console.WriteLine (e.StackTrace)
End Try
35 End If
36 Monitor.Exit(Me) 
End SyncLock
37 End Sub
38 End Class
39 Public Class Knife
40 Private Shared mKnifeAvailable As Boolean = True
41 Private Shared mOwner As String ="Nobody"
42 Private Readonly Property OwnsUtensi1() As String
43 Get
44 Return mOwner
45 End Get
46 End Property
47 Public Sub GrabKnifetByVal a As Programmer)
48 Console.WriteLine(Thread.CurrentThread.Name & _
"trying to grab the knife.")
49 Console.WriteLine(Me.OwnsUtensil & "has the knife.")
50 Monitor.Enter(Me) 'SyncLock (aKnife)'
51 If mKnifeAvailable Then
52 mKnifeAvailable = False
53 a.HasKnife = True
54 mOwner = a.MyName
55 Console.WriteLine(a.MyName&"just got the knife.waiting")
56 Try
Thread.Sleep(100) 
Catch e As Exception 
Console.WriteLine (e.StackTrace) 
End Try
57 End If
58 Monitor.Exit(Me)
59 End Sub
60 End Class
61 Public Class Programmer
62 Private mName As String
63 Private Shared mFork As Fork
64 Private Shared mKnife As Knife
65 Private mHasKnife As Boolean
66 Private mHasFork As Boolean
67 Shared Sub New()
68 mFork = New Fork()
69 mKnife = New Knife()
70 End Sub
71 Public Sub New(ByVal theName As String)
72 mName = theName 
73 End Sub 
74 Public Readonly Property MyName() As String
75 Get 
76 Return mName
77 End Get 
78 End Property 
79 Public Property HasKnife() As Boolean
80 Get
81 Return mHasKnife
82 End Get
83 Set(ByVal Value As Boolean)
84 mHasKnife = Value
85 End Set
86 End Property
87 Public Property HasFork() As Boolean
88 Get
89 Return mHasFork
90 End Get
91 Set(ByVal Value As Boolean)
92 mHasFork = Value
93 End Set
94 End Property
95 Public Sub Eat()
96 Do Until Me.HasKnife And Me.HasFork
97 Console.Writeline(Thread.CurrentThread.Name&"is in the thread.")
98 If Rnd() < 0.5 Then
99 mFork.GrabFork(Me)
100 Else
101 mKnife.GrabKnife(Me)
102 End If
103 Loop
104 MsgBox(Me.MyName & "can eat!")
105 mKnife = New Knife()
106 mFork= New Fork()
107 End Sub
108 End Class
Заранее благодарен!

Последний раз редактировалось Stilet; 05.04.2011 в 09:58.
Nicrom вне форума Ответить с цитированием
Старый 04.04.2011, 10:33   #2
Hollander
Участник клуба
 
Аватар для Hollander
 
Регистрация: 03.05.2007
Сообщений: 1,189
По умолчанию

Попробуй http://www.developerfusion.com/tools.../vb-to-csharp/
Hollander вне форума Ответить с цитированием
Старый 04.04.2011, 23:10   #3
Nicrom
 
Регистрация: 02.04.2011
Сообщений: 3
По умолчанию

Цитата:
Сообщение от Hollander Посмотреть сообщение
Спсибо, я уже пробывал. К сожалени., конвертер выдает -- line 10 col 47: this symbol not expected in EndOfStmt, а так я не очень силен в VB.NET, то не могу понять в чем ошибкаю
P.S. В конвертер вкидываю данный текст программы
Код:
Option Strict On
Imports System.Threading
Module Modulel
Sub Main()
Dim Tom As New Programmer( "Tom")
Dim Bob As New Programmer( "Bob")
Dim aThreadStart As New ThreadStart(AddressOf Tom.Eat)
Dim aThread As New Thread(aThreadStart)
aThread.Name= "Tom"
Dim bThreadStart As New ThreadStarttAddressOf Bob.Eat)
Dim bThread As New Thread(bThreadStart)
bThread.Name = "Bob"
aThread.Start()
bThread.Start()
End Sub
End Module
Public Class Fork
Private Shared mForkAvaiTable As Boolean = True
Private Shared mOwner As String = "Nobody"
Private Readonly Property OwnsUtensil() As String
Get
Return mOwner
End Get
End Property
Public Sub GrabForktByVal a As Programmer)
Console.Writel_ine(Thread.CurrentTh read.Name &_ 
"trying to grab the fork.")
Console.WriteLine(Me.OwnsUtensil & "has the fork.") . .
Monitor.Enter(Me) 'SyncLock (aFork)'
If mForkAvailable Then
a.HasFork = True
mOwner = a.MyName
mForkAvailable = False
Console.WriteLine(a.MyName&"just got the fork.waiting")
Try
Thread.Sleep(100) Catch e As Exception Console.WriteLine (e.StackTrace)
End Try
End If
Monitor.Exit(Me) 
End SyncLock
End Sub
End Class
Public Class Knife
Private Shared mKnifeAvailable As Boolean = True
Private Shared mOwner As String ="Nobody"
Private Readonly Property OwnsUtensi1() As String
Get
Return mOwner
End Get
End Property
Public Sub GrabKnifetByVal a As Programmer)
Console.WriteLine(Thread.CurrentThr ead.Name & _
"trying to grab the knife.")
Console.WriteLine(Me.OwnsUtensil & "has the knife.")
Monitor.Enter(Me) 'SyncLock (aKnife)'
If mKnifeAvailable Then
mKnifeAvailable = False
a.HasKnife = True
mOwner = a.MyName
Console.WriteLine(a.MyName&"just got the knife.waiting")
Try
Thread.Sleep(100) 
Catch e As Exception 
Console.WriteLine (e.StackTrace) 
End Try
End If
Monitor.Exit(Me)
End Sub
End Class
Public Class Programmer
Private mName As String
Private Shared mFork As Fork
Private Shared mKnife As Knife
Private mHasKnife As Boolean
Private mHasFork As Boolean
Shared Sub New()
mFork = New Fork()
mKnife = New Knife()
End Sub
Public Sub New(ByVal theName As String)
mName = theName 
End Sub 
Public Readonly Property MyName() As String
Get 
Return mName
End Get 
End Property 
Public Property HasKnife() As Boolean
Get
Return mHasKnife
End Get
Set(ByVal Value As Boolean)
mHasKnife = Value
End Set
End Property
Public Property HasFork() As Boolean
Get
Return mHasFork
End Get
Set(ByVal Value As Boolean)
mHasFork = Value
End Set
End Property
Public Sub Eat()
Do Until Me.HasKnife And Me.HasFork
Console.Writeline(Thread.CurrentThr ead.Name&"is in the thread.")
If Rnd() < 0.5 Then
mFork.GrabFork(Me)
Else
mKnife.GrabKnife(Me)
End If
Loop
MsgBox(Me.MyName & "can eat!")
mKnife = New Knife()
mFork= New Fork()
End Sub
End Class

Последний раз редактировалось Stilet; 05.04.2011 в 09:58.
Nicrom вне форума Ответить с цитированием
Старый 05.04.2011, 09:49   #4
wm_leviathan
Форумчанин
 
Аватар для wm_leviathan
 
Регистрация: 17.02.2010
Сообщений: 399
По умолчанию

странный код какой то. создал VB консольное приложение, скопировал код и.... я вах получил около 40 ошибок, мб даже и больше на VB прогал последний раз (как раз учился на нем) лет 7 назад тогда еще 6й был. вообщем кое как вроде довел до ума код
VB
Код:
Option Strict On
Imports System.Threading

Module Modulel
    Sub Main()
        Dim Tom As New Programmer("Tom")
        Dim Bob As New Programmer("Bob")
        Dim aThreadStart As New ThreadStart(AddressOf Tom.Eat)
        Dim aThread As New Thread(aThreadStart)
        aThread.Name = "Tom"
        Dim bThreadStart As New ThreadStart(AddressOf Bob.Eat)
        Dim bThread As New Thread(bThreadStart)
        bThread.Name = "Bob"
        aThread.Start()
        bThread.Start()
    End Sub
End Module
Public Class Fork
    Private Shared mForkAvaiTable As Boolean = True
    Private Shared mOwner As String = "Nobody"
    Dim mForkAvailable As Boolean

    Private ReadOnly Property OwnsUtensil() As String
        Get
            Return mOwner
        End Get
    End Property
    Public Sub GrabForktByVal(ByVal a As Programmer)
        Console.WriteLine(Thread.CurrentThread.Name & "trying to grab the fork.")
        Console.WriteLine(Me.OwnsUtensil & "has the fork.")
        Monitor.Enter(Me) 'SyncLock (aFork)'
        If mForkAvailable Then
            a.HasFork = True
            mOwner = a.MyName
            mForkAvailable = False
            Console.WriteLine(a.MyName & "just got the fork.waiting")
            Try
                Thread.Sleep(100)
            Catch e As Exception
                Console.WriteLine(e.StackTrace)

            End Try


        End If
        Monitor.Exit(Me)
        'End SyncLock'
    End Sub

    Sub GrabFork(ByVal programmer As Programmer)
        Throw New NotImplementedException
    End Sub

End Class
Public Class Knife
    Private Shared mKnifeAvailable As Boolean = True
    Private Shared mOwner As String = "Nobody"
    Dim OwnsUtensil As String

    Private ReadOnly Property OwnsUtensi1() As String
        Get
            Return mOwner
        End Get
    End Property
    Public Sub GrabKnifetByVal(ByVal a As Programmer)
        Console.WriteLine(Thread.CurrentThread.Name & "trying to grab the knife.")
        Console.WriteLine(Me.OwnsUtensil & "has the knife.")
        Monitor.Enter(Me) 'SyncLock (aKnife)'
        If mKnifeAvailable Then
            mKnifeAvailable = False
            a.HasKnife = True
            mOwner = a.MyName
            Console.WriteLine(a.MyName & "just got the knife.waiting")
            Try
                Thread.Sleep(100)
            Catch e As Exception
                Console.WriteLine(e.StackTrace)
            End Try
        End If
        Monitor.Exit(Me)
    End Sub

    Sub GrabKnife(ByVal programmer As Programmer)
        Throw New NotImplementedException
    End Sub

End Class
Public Class Programmer
    Private mName As String
    Private Shared mFork As Fork
    Private Shared mKnife As Knife
    Private mHasKnife As Boolean
    Private mHasFork As Boolean
    Shared Sub New()
        mFork = New Fork()
        mKnife = New Knife()
    End Sub
    Public Sub New(ByVal theName As String)
        mName = theName
    End Sub
    Public ReadOnly Property MyName() As String
        Get
            Return mName
        End Get
    End Property
    Public Property HasKnife() As Boolean
        Get
            Return mHasKnife
        End Get
        Set(ByVal Value As Boolean)
            mHasKnife = Value
        End Set
    End Property
    Public Property HasFork() As Boolean
        Get
            Return mHasFork
        End Get
        Set(ByVal Value As Boolean)
            mHasFork = Value
        End Set
    End Property
    Public Sub Eat()
        Do Until Me.HasKnife And Me.HasFork
            Console.WriteLine(Thread.CurrentThread.Name & "is in the thread.")
            If Rnd() < 0.5 Then
                mFork.GrabFork(Me)
            Else
                mKnife.GrabKnife(Me)
            End If
        Loop
        MsgBox(Me.MyName & "can eat!")
        mKnife = New Knife()
        mFork = New Fork()
    End Sub
End Class
wm_leviathan вне форума Ответить с цитированием
Старый 05.04.2011, 09:50   #5
wm_leviathan
Форумчанин
 
Аватар для wm_leviathan
 
Регистрация: 17.02.2010
Сообщений: 399
По умолчанию

по ссылке что дал Hollander конвертнул в c# получил
Код:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Threading;
using Microsoft.VisualBasic;



static class Modulel
{

    public static void Main()
    {
        Programmer Tom = new Programmer("Tom");
        Programmer Bob = new Programmer("Bob");
        ThreadStart aThreadStart = new ThreadStart(Tom.Eat);
        Thread aThread = new Thread(aThreadStart);
        aThread.Name = "Tom";
        ThreadStart bThreadStart = new ThreadStart(Bob.Eat);
        Thread bThread = new Thread(bThreadStart);
        bThread.Name = "Bob";
        aThread.Start();
        bThread.Start();
    }
}

public class Fork
{
    private static bool mForkAvaiTable = true;
    private static string mOwner = "Nobody";

    bool mForkAvailable;
    private string OwnsUtensil
    {
        get { return mOwner; }
    }
    public void GrabForktByVal(Programmer a)
    {
        Console.WriteLine(Thread.CurrentThread.Name + "trying to grab the fork.");
        Console.WriteLine(this.OwnsUtensil + "has the fork.");
        Monitor.Enter(this);
        //SyncLock (aFork)'
        if (mForkAvailable)
        {
            a.HasFork = true;
            mOwner = a.MyName;
            mForkAvailable = false;
            Console.WriteLine(a.MyName + "just got the fork.waiting");
            try
            {
                Thread.Sleep(100);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);

            }


        }
        Monitor.Exit(this);
        //End SyncLock'
    }

    public void GrabFork(Programmer programmer)
    {
        throw new NotImplementedException();
    }

}
public class Knife
{
    private static bool mKnifeAvailable = true;
    private static string mOwner = "Nobody";

    string OwnsUtensil;
    private string OwnsUtensi1
    {
        get { return mOwner; }
    }
    public void GrabKnifetByVal(Programmer a)
    {
        Console.WriteLine(Thread.CurrentThread.Name + "trying to grab the knife.");
        Console.WriteLine(this.OwnsUtensil + "has the knife.");
        Monitor.Enter(this);
        //SyncLock (aKnife)'
        if (mKnifeAvailable)
        {
            mKnifeAvailable = false;
            a.HasKnife = true;
            mOwner = a.MyName;
            Console.WriteLine(a.MyName + "just got the knife.waiting");
            try
            {
                Thread.Sleep(100);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
        }
        Monitor.Exit(this);
    }

    public void GrabKnife(Programmer programmer)
    {
        throw new NotImplementedException();
    }

}
public class Programmer
{
    private string mName;
    private static Fork mFork;
    private static Knife mKnife;
    private bool mHasKnife;
    private bool mHasFork;
    static Programmer()
    {
        mFork = new Fork();
        mKnife = new Knife();
    }
    public Programmer(string theName)
    {
        mName = theName;
    }
    public string MyName
    {
        get { return mName; }
    }
    public bool HasKnife
    {
        get { return mHasKnife; }
        set { mHasKnife = value; }
    }
    public bool HasFork
    {
        get { return mHasFork; }
        set { mHasFork = value; }
    }
    public void Eat()
    {
        while (!(this.HasKnife & this.HasFork))
        {
            Console.WriteLine(Thread.CurrentThread.Name + "is in the thread.");
            if (VBMath.Rnd() < 0.5)
            {
                mFork.GrabFork(this);
            }
            else
            {
                mKnife.GrabKnife(this);
            }
        }
        Interaction.MsgBox(this.MyName + "can eat!");
        mKnife = new Knife();
        mFork = new Fork();
    }
}
обязательно надо делать project->add reference->Microsoft Visual Basic вот вроде все. правда вылетает исключение в этой строке
Код:
throw new NotImplementedException();
ну это я думаю ты сам уже поковыряешь, углубляться в прогу у меня нет желания
wm_leviathan вне форума Ответить с цитированием
Старый 05.04.2011, 16:03   #6
Nicrom
 
Регистрация: 02.04.2011
Сообщений: 3
По умолчанию

Большое спасибо)))))))))))
Nicrom вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Перевести с СИ++ на СИ stepanov_ivan Помощь студентам 1 02.01.2011 23:08
ПЕРЕВЕСТИ НА c++ daniil2010 Помощь студентам 1 20.04.2010 19:51
ПЕРЕВЕСТИ НА c++ daniil2010 Помощь студентам 1 19.04.2010 18:28
Перевести на СИ DartDayring Общие вопросы C/C++ 4 30.03.2010 17:46
перевести из C++ в C AlinAA Фриланс 8 06.03.2009 20:41